Question

I'm trying to make a snapshot of a directory, like it described in apple documentation.

I want to use scandir() function. Here it is from documentation:

scandir(const char *dirname, struct dirent ***namelist, int (*select)(const struct dirent *),
     int (*compar)(const struct dirent **, const struct dirent **));

I don't understand how to use it properly. Here is how I implement my snapshot function:

-(void)createFolderSnapshotWithPath:(NSString *)pathString
{

NSLog(@"snap");
const char *pathsToWatch=[pathString UTF8String];

struct dirent snapshot;


scandir(pathsToWatch, &snapshot, NULL, NULL); // I have a warning here because 
                                              // &snapshot used wrong here


NSLog(@"snap result: %llu | %s | %i",snapshot.d_ino, snapshot.d_name, snapshot.d_type);
// snapshot.d_type returns 0 which means unknown type (DT_UNKNOWN) 

}

Here is a dirent struct:

struct dirent {
    ino_t d_ino;            /* file number of entry */
    __uint16_t d_reclen;        /* length of this record */
    __uint8_t  d_type;      /* file type, see below */
    __uint8_t  d_namlen;        /* length of string in d_name */
    char d_name[__DARWIN_MAXNAMLEN + 1];    /* name must be no longer than this */
};

I don't understand hot to proper create dirent struct and how to proper use it in scandir() function.

All I want from that function is an array that I could use later when I will compare it with another snapshot.

Was it helpful?

Solution

scandir() allocates an array of entries.

So you should declare the 2nd paramter like this:

struct dirent ** snapshot = NULL;

And after successfully having called scandir() you can access its members like this:

printf("%s", snapshot[0]->d_name);

for example.

If the array along with its entries isn't used anymore, 1st free the entries looping over all and calling

free(snapshot[i]);

for each entry and finally do:

free(snapshot);

All this together might look like this:

#include <dirent.h>

int main(void)
{
  struct dirent ** namelist = NULL;
  int n = scandir(".", &namelist, NULL, alphasort);
  if (n < 0)
  {
    perror("scandir");
  }
  else
  {
    while (n--) 
    {
      printf("%s\n", namelist[n]->d_name);
      free(namelist[n]);
    }

    free(namelist);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top