我正在进行POSIX C学习练习,涉及递归列出指定目录中的文件/文件夹.该程序作为一个或多个目录的参数.我可以列出初始目录的内容很好,但有一个递归问题.我在递归函数调用的参数中传递的方式有问题吗?
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
void listdir(char *argv[])
{
DIR *mydirhandle;
struct dirent *mydirent;
struct stat statinfo;
int n = 1;
while(argv[n] != NULL)
{
if((mydirhandle = opendir(argv[n])) == NULL)
{
perror("opendir");
exit(1);
}
printf("%s/\n", argv[n]);
while((mydirent = readdir(mydirhandle)) != NULL)
{
if((strcmp(mydirent->d_name, ".") == 0) || (strcmp(mydirent->d_name, "..") == 0))
{
continue;
}
else
{
printf("\t%s\n", mydirent->d_name);
//check if next entry is a directory
if(mydirent->d_type == DT_DIR)
{
//is current directory being passed correctly here?
listdir(mydirent->d_name);
}
}
}
n++;
closedir(mydirhandle);
}
}
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("usage: %s <directory>\n", argv[0]);
return 0;
}
listdir(argv);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该d_name成员struct dirent是有问题的项目的基本名称.所以,如果你要经历这样的目录:
.
..
where-is/
pancakes/
.
..
house
Run Code Online (Sandbox Code Playgroud)
一旦你进入where-is,你会尝试,listdir("pancakes")但这是行不通的,因为你需要listdir("where-is/pancakes").
在获得可以传递给下一个listdir调用的内容之前,您需要将它与您正在查找的目录的名称相结合.
你会想要替换这样的东西:
listdir(mydirent->d_name);
Run Code Online (Sandbox Code Playgroud)
这样的事情:
char *next_dir = malloc(strlen(argv[n]) + strlen(mydirent->d_name) + 1 + 1);
sprintf(next_dir, "%s/%s", argv[n], mydirent->d_name);
listdir(next_dir);
free(next_dir);
Run Code Online (Sandbox Code Playgroud)
或者,您可以chdir在输入目录时进入目录,然后chdir在完成后备份.