有效地遍历目录树由opendir(),readdir的()和closedir() [英] Efficiently Traverse Directory Tree with opendir(), readdir() and closedir()

查看:739
本文介绍了有效地遍历目录树由opendir(),readdir的()和closedir()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C例程执行opendir(),readdir的()和closedir()为我遍历目录结构的方法。然而,READDIR()返回各自的dirent结构似乎并没有提供一个有用的办法,我得到一组指向DIR的,我需要递归到该目录的子目录中。

The C routines opendir(), readdir() and closedir() provide a way for me to traverse a directory structure. However, each dirent structure returned by readdir() does not seem to provide a useful way for me to obtain the set of pointers to DIR that I would need to recurse into the directory subdirectories.

当然,他们给我的文件的名字,这样我就可以要么名称附加到目录路径和stat()和执行opendir()他们,我也可以通过CHDIR改变进程的当前工作目录( ),并回滚通过CHDIR(..)。

Of course, they give me the name of the files, so I could either append that name to the directory path and stat() and opendir() them, or I could change the current working directory of the process via chdir() and roll it back via chdir("..").

与第一种方法的问题是,如果目录路径的长度足够大,那么成本传递含有它执行opendir()将超重打开一个目录的成本的字符串。如果你是多一点理论上,你可以说你的复杂性会在超出线性时间增加(在目录树中的(相对)文件名的总字符数)。

The problem with the first approach is that if the length of the directory path is great enough, then the cost to pass a string containing it to opendir() will overweight the cost of opening a directory. If you are a bit more theoretical, you could say your complexity could increase beyond linear time (in the total character count of the (relative) filenames in the directory tree).

此外,第二种方法有问题。由于每个进程都有一个单一的当前工作目录,除了一个线程在多线程应用程序阻止。另外,我不知道如果当前的工作目录只是一个单纯的便利(即相对路径将之前的文件系统查询,追加到它)。如果是,这种方法将是低效率的太

Also, the second approach has a problem. Since each process has a single current working directory, all but one thread will have to block in a multithreaded application. Also, I don't know if the current working directory is just a mere convenience (i.e., the relative path will be appended to it prior to a filesystem query). If it is, this approach will be inefficient too.

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

I am accepting alternatives to these functions. So how is it one can traverse a UNIX directory tree efficiently (linear time in the total character count of the files under it)?

推荐答案

你试过 FTW()又名文件树径<​​/ STRONG>

Have you tried ftw() aka File Tree Walk ?

从SNIPPIT 男子3 FTW

INT FTW(为const char *目录,INT(* FN)(为const char *文件,常量结构统计*某人,INT标志),INT nopenfd);

FTW()通过从指定目录dir开始的目录树散步。对于树中的每个找到的条目,它调用的入口,一个指向STAT(2)结构的入口和一个int标志的完整路径FN()

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

这篇关于有效地遍历目录树由opendir(),readdir的()和closedir()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆