我一直在尝试在 C 上实现类似 ls -R 的东西时遇到问题,问题是我需要列表递归地列出从给定目录开始的所有内容,然后对从列表中获得的那些常规文件进行处理。 这是我目前所拥有的:
void ls(char* path){
DIR *directory;
struct dirent *filei;
struct stat stats;
directory = opendir(path);
if (directory != NULL)
{
while ((filei=readdir(directory))!=NULL){
stat(filei->d_name, &stats);
printf(" %s\n", filei->d_name);
if (S_ISDIR(stats.st_mode)){
char *buf = malloc(strlen(path)+strlen(filei->d_name)+2);
strcpy(buf,path);
strcat(buf,"/");
strcat(buf,filei->d_name);
ls(buf);
}
}
closedir(directory);
}
else{
printf("Error.\n");
}
}
它根本不起作用,它显示的文件甚至不在我正在使用的文件夹中。 有什么想法吗? 谢谢。
最佳答案
您不得递归到“.”和“..”条目。您至少会无限递归到同一个目录,或者 up 很糟糕。过滤器:
if (!strcmp(filei->d_name,".") && (!strcmp(filei->d_name,"..")) ls(buf);
您还必须 stat
到完整路径:
char *buf = malloc(strlen(path)+strlen(filei->d_name)+2);
strcpy(buf,path);
strcat(buf,"/");
strcat(buf,filei->d_name);
stat(buf, &stats);
if (S_ISDIR(stats.st_mode)) {
if (!strcmp(filei->d_name,".") && (!strcmp(filei->d_name,"..")) {
ls(buf);
}
}
关于c - 递归列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37915049/