gpt4 book ai didi

c - 操作系统 X : trouble with dirent struct attribute of scandir() function

转载 作者:行者123 更新时间:2023-11-30 15:46:39 24 4
gpt4 key购买 nike

我正在尝试制作目录的快照,如 apple documentation 中所述。 。

我想使用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)

}

这是一个直接结构:

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

free(namelist);
}
}

关于c - 操作系统 X : trouble with dirent struct attribute of scandir() function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18165933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com