我可以帮你进行翻译。需要使用C语言递归地打印文件和目录(包括子目录和文件),以下是代码示例:
当我运行上述程序时,根据文件结构,可能会有两种不同的输出结果。
一种可能情况是(这种情况下,它会说Untitled.txt在random文件夹中,但实际上并不在):
如果我将Untitled.txt重命名为类似apple.txt的名称,则它将正常打印。这使我相信,它是按字母顺序排列的。
我该如何使其先打印所有文件,然后进入文件夹并打印其中的所有文件,然后重复此过程?因此,打印文件>进入文件夹>重复。
char filepath[250], filename[250];
void listdir(char *dir)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL)
{
fprintf(stderr,"cannot open directory: %s\n", dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL)
{
if(lstat(entry->d_name, &statbuf) == 0)
{
if(statbuf.st_mode & S_IFDIR)
{
/* Found a directory, but ignore . and .. */
if(strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
continue;
// Concatenate directory name
strcat(filepath, entry->d_name);
strcat(filepath, "/");
/* Recurse at a new indent level */
listdir(entry->d_name);
}
else
{
// Concatenate file name
strcpy(filename, filepath);
strcat(filename, entry->d_name);
puts(filename);
}
}
}
chdir("..");
closedir(dp);
}
我注意到这段代码存在两个问题。假设这是我的文件结构:
index.c
main.c
test.o
test/hello.txt
test/Untitled.txt
test/random/
当我运行上述程序时,根据文件结构,可能会有两种不同的输出结果。
一种可能情况是(这种情况下,它会说Untitled.txt在random文件夹中,但实际上并不在):
index.c
main.c
test.o
test/hello.txt
test/random/Untitled.txt
如果我将Untitled.txt重命名为类似apple.txt的名称,则它将正常打印。这使我相信,它是按字母顺序排列的。
我该如何使其先打印所有文件,然后进入文件夹并打印其中的所有文件,然后重复此过程?因此,打印文件>进入文件夹>重复。
path
在哪里?你填充了变量filepath
但是使用了path
,是这样吗? - undefinedrandom
的同一级目录下还有另一个目录,会发生什么?您从filepath
中没有删除当前目录名,因此当退出random
并进入另一个目录后将生成无效的路径。这可能也是您问题的原因。 - undefined