gpt4 book ai didi

c - c中的迭代目录遍历

转载 作者:太空宇宙 更新时间:2023-11-04 03:02:16 24 4
gpt4 key购买 nike

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

sample 运行

$ ./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

最佳答案

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

关于c - c中的迭代目录遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10047762/

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