gpt4 book ai didi

c - 使用 opendir()、readdir() 和 closedir() 高效地遍历目录树

转载 作者:太空狗 更新时间:2023-10-29 16:32:05 26 4
gpt4 key购买 nike

C 例程 opendir()、readdir() 和 closedir() 为我提供了一种遍历目录结构的方法。但是,readdir() 返回的每个 dirent 结构似乎都没有为我提供一种有用的方法来获取指向 DIR 的指针集,我需要递归到目录子目录中。

当然,他们给了我文件名,所以我可以将该名称附加到目录路径和 stat() 和 opendir() 它们,或者我可以通过 chdir( ) 并通过 chdir("..") 将其回滚。

第一种方法的问题在于,如果目录路径的长度足够长,那么将包含它的字符串传递给 opendir() 的成本将超过打开目录的成本。如果您更偏理论一点,您可以说您的复杂性可能会增加到超过线性时间(在目录树中(相对)文件名的总字符数中)。

另外,第二种方法也有问题。由于每个进程都有一个当前工作目录,因此在多线程应用程序中,除了一个线程外,其他所有线程都必须阻塞。另外,我不知道当前工作目录是否只是为了方便(即,相对路径将在文件系统查询之前附加到它)。如果是,这种方法也将是低效的。

我接受这些功能的替代品。那么如何有效地遍历 UNIX 目录树(其下文件的总字符数的线性时间)?

最佳答案

您是否尝试过 ftw() 又名 File Tree Walk

来自 man 3 ftw 的片段:

int ftw(const char *dir, int (*fn)(const char *file, const struct stat *sb, int flag), int nopenfd);

ftw() walks through the directory tree starting from the indicated directory dir. For each found entry in the tree, it calls fn() with the full pathname of the entry, a pointer to the stat(2) structure for the entry and an int flag

关于c - 使用 opendir()、readdir() 和 closedir() 高效地遍历目录树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2312110/

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