gpt4 book ai didi

C OS X 将目录内容读入字符串数组

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:44 25 4
gpt4 key购买 nike

我正在尝试获取目录的内容。理想情况下,我想将它们存储在一个字符串数组中。除了打开目录、遍历其内容并在其运行时填充数组之外,有没有其他方法可以在 c 语言中执行此操作?

我在运行 OS X 10.9 的系统上工作

最佳答案

您可以使用 POSIX scandir 获取分配的目录列表函数,它采用路径和可选的过滤和排序回调,并返回 dirent 结构的数组。 OS X 还提供了 an equivalent function它采用 block 而不是回调来进行排序和过滤。

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

检索未排序的条目列表非常简单:

int num_entries;
struct dirent **entries = NULL;

num_entries = scandir("/", &entries, NULL, NULL);

for(int i = 0; i < num_entries; i++)
puts(entries[i]->d_name);

//entries is ours to free
for(int i = 0; i < num_entries; i++)
free(entries[i]);
free(entries);

POSIX 还提供了一个预制的排序函数,可与 scandir 一起使用以按字母顺序排序。要使用它,只需将 alphasort 作为最后一个参数传递即可。

小心 scandir 返回错误 (-1)。上述代码的结构无需显式检查,但在更精细的用途中可能无法做到这一点。

关于C OS X 将目录内容读入字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21332694/

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