gpt4 book ai didi

c - 递归打印目录及其子目录中所有文件的文件路径

转载 作者:行者123 更新时间:2023-11-30 19:11:04 28 4
gpt4 key购买 nike

我正在开发一个项目,该项目应该打印出 C 目录及其所有子目录中所有文件的所有文件路径。基本上,它最终意味着模拟 Linux 中的 find 实用程序。

我有以下代码:

void read_sub(char * sub_dir){
DIR *sub_dp = opendir(sub_dir);//open a directory stream
struct dirent * sub_dirp;//define
struct stat buf;//define a file status structure
char temp1[]=".";
char temp2[]="..";
char temp3[]="/";

if(sub_dp!=NULL){ //Check if the directory opened successfully

while((sub_dirp=readdir(sub_dp))!=NULL){ //until we've read every entry one by one

char * temp = sub_dirp -> d_name; //get the name

if(strcmp(temp, temp1)!=0 && strcmp(temp, temp2)!=0){ //Ignores . and .. in the directory

char *temp_sub = temp3; // This is '/'
temp_sub = strcat(temp_sub, temp); // Adds '/' before the name of the entry


//now you can add the / in front of the entry's name
char* temp_full_path=malloc(sizeof(char)*2000); //Create a variable to hold the full path

//Place the passed directory at the front of the path and add the name of the file to the end
temp_full_path=strcpy(temp_full_path,sub_dir);
strcat(temp_full_path,temp_sub);

//try to open the file path we just created
DIR * subsubdp = opendir(temp_full_path);


//if not null, we've found a subdirectory, otherwise it's a file
if(subsubdp!=NULL){
//close the stream because it'll be reopened in the recursive call.
closedir(subsubdp);
read_sub(temp_full_path);//call the recursive function call.
}else{
printf("%s\n",temp_full_path);
}
}
}//end of while loop
closedir(sub_dp);//close the stream
}else{
printf("cannot open directory\n");
exit(2);
}
}

我通过直接传递“testdir”来运行它,这是一个具有以下结构的目录:

testdir/
|-- dir1
| |-- dir2
| | |-- test5
| | `-- test6
| |-- test3
| `-- test4
|-- dir3
| |-- test7
| `-- test8
|-- test1
`-- test2

因此,它应该输出如下内容:

testdir/dir1/dir2/test5
testdir/dir1/dir2/test6
testdir/dir1/test3
testdir/dir1/test4

等等。然而,实际结果是:

testdir/dir1/dir2/test6
testdir/dir1/dir2/test6test5
testdir/dir1/dir2test3
testdir/dir1/dir2test3test4
testdir/dir1test1
testdir/dir1test1dir3
testdir/dir1test1dir3test2

所以我猜它在运行时可能无法正确清除完整文件路径?另外,它似乎实际上并没有输入 dir3 来打印 test7 和 test8。我做错了什么?谢谢。

最佳答案

您没有为目标字符串分配足够的空间。您至少需要 PATH_MAX 字节。

尝试

char temp1[PATH_MAX] = ".";
char temp2[PATH_MAX] = "..";
char temp3[PATH_MAX] = "/";

事实上,编译器只会分配足够的空间来分别保存初始化字符串 (2, 3, 2)。所以你的程序表现出未定义的行为。我建议使用 snprintf() 而不是 strcat(),因为它是直接的并且不那么昂贵。每次调用 strcat() 时,它都会迭代搜索目标字符串的当前结尾,直到找到终止 '\0'

此外,请尝试使用最少的缩进级别,因为代码很快就会变得非常难以阅读。

关于c - 递归打印目录及其子目录中所有文件的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40697317/

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