1

我一直在尝试用 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
4

1 回答 1

2

We can't see what Enqueue() does, but odds are high to you put a pointer to a string on the queue instead of a copy of the string. So yes, what you dequeue won't be the same string again since you keep modifying name in the while loop.

于 2012-04-06T18:51:44.813 回答