【问题标题】:Iterative Directory Traversal in cc中的迭代目录遍历
【发布时间】:2012-04-06 18:42:44
【问题描述】:

我一直在尝试用 c 编写一个迭代目录。我从一个标准的递归目录遍历开始,它按预期工作。现在我正在尝试使用队列结构将其转换为迭代版本,但它的行为出乎意料。不知何故,子目录中的一个文件被添加到我的队列中,当尝试将文件作为目录打开时,程序显然失败了。

代码片段

char *dirName;
DIR *dp;
struct dirent *d_ent;
struct stat s;
char name[80];

...

while(!IsEmpty(q)){
    dirName = FrontAndDequeue(q);
    if((dp = opendir(dirName)) == NULL) {
        printf("ERROR: dirRec: %s: %s\n", dirName, strerror(errno));
    } else {
        while((d_ent = readdir(dp)) != NULL) {
            if((strcmp(d_ent->d_name, "..") != 0) && (strcmp(d_ent->d_name, ".") != 0)){
                strcpy(name, dirName);
                strcat(name, "/");
                strcat(name, d_ent->d_name);
                if(lstat(name, &s) < 0) {
                    printf("ERROR: dirDepth: %s: %s\n", name, strerror(errno));
                } else {
                    if(S_ISDIR(s.st_mode)) {      /* Process directories. */
                        printf("Directory : %s\n", name);
                        Enqueue(name, q);
                    } else {              /* Process non-directories. */
                        printf("File      : %s\n", name);
                    } 
                }
            }
        }
        closedir(dp);

样品运行

$ ./dir .
File      : ./dir.c
File      : ./dir.cpp
File      : ./dir.exe
File      : ./dir.exe.stackdump
File      : ./dirRec.c
File      : ./dirRec.exe
File      : ./fatal.h
File      : ./Makefile
File      : ./queue.c
File      : ./queue.h
File      : ./stackli.c
File      : ./stackli.h
Directory : ./testL1a
Directory : ./testL1b
File      : ./testL1b/New Bitmap Image.bmp
ERROR: dirRec: ./testL1b/New Bitmap Image.bmp: Not a directory

【问题讨论】:

    标签: c filesystems queue dir


    【解决方案1】:

    我们看不到 Enqueue() 做了什么,但是你很有可能在队列中放置一个指向字符串的指针而不是字符串的副本。所以,是的,你出队的内容将不再是同一个字符串,因为你在 while 循环中不断修改 name

    【讨论】:

    • 这确实引发了另一个问题,将字符串复制到队列中的最佳方法是什么(我已经切换到 C++ 和 STL::queue)。
    • 点击“”按钮提问。
    猜你喜欢
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多