c-OS X:scandir()函数的dirent struct属性出现问题



我正在尝试制作一个目录的快照,就像苹果文档中描述的那样。

我想使用scandir()函数。这是来自文档:

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

我不知道如何正确使用它。以下是我如何实现快照功能:

-(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) 
}

这是一个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 */
};

我不知道如何正确创建dirent struct以及如何在scandir()函数中正确使用它。

我只想从该函数中得到一个数组,稍后将其与另一个快照进行比较时可以使用该数组。

scandir()分配一个条目数组。

所以你应该这样声明第二个参数:

struct dirent ** snapshot = NULL;

在成功调用scandir()后,您可以访问其成员,如下所示:

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

例如。

如果数组及其条目不再使用,请首先释放所有循环的条目并调用

free(snapshot[i]);

对于每个条目,并最终执行:

free(snapshot);

所有这些加在一起可能看起来像这样:

#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("%sn", namelist[n]->d_name);
      free(namelist[n]);
    }
    free(namelist);
  }
}

最新更新