问题描述
我想递归地检索给定路径中包含的所有文件,目录和子目录。但是当我的代码到达第二级(目录内的一个目录)时,我遇到了一个问题:不是打开内部目录来搜索它的内容,而是抛出一个错误。这里是我所做的:
$ $ p $ $ $ $ $ $ $ getFile(char * path)
{
DIR * dir;
struct dirent * ent; ((dir = opendir(path))!= NULL){
/ *打印目录* /
中的所有文件和目录,((ent = readdir(dir))! = NULL){
if((strcmp(ent-> d_name,..)!= 0)&&(strcmp(ent-> d_name,。)!= 0)) {
printf(%s,ent-> d_name);
if(ent-> d_type == DT_DIR){
printf(/ \\\
);
getFile(ent-> d_name);
}
else {
printf(\\\
);
}
} //条件结束
} // while循环结束
closedir(dir);
$ b
递归调用 getFile
,你只能用你刚才读到的目录的名字来调用它。它不是完整的路径,这是你需要的。
$ b
类似于这样:
((strlen(path)+ strlen(ent-> d_name)+ 1)pre $ if $ {code $ if $ > PATH_MAX)
{
printf(Path to long \\\
);
return;
}
char fullpath [PATH_MAX + 1];
strcpy(fullpath,path);
strcat(fullpath,/);
strcat(fullpath,ent-> d_name); //改正
getFile(fullpath);
}
I want to retrieve all the files, directories and subdirectories contained within a given path, recursively. But I have a problem when my code reaches the second level (a directory within a directory): instead of opening the inner directory to search its contents, it throws an error. Here is what I have done:
void getFile(char *path)
{
DIR *dir;
struct dirent *ent;
if ((dir = opendir(path)) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir(dir)) != NULL) {
if((strcmp(ent->d_name,"..") != 0) && (strcmp(ent->d_name,".") != 0)){
printf ("%s", ent->d_name);
if(ent->d_type == DT_DIR){
printf("/\n");
getFile(ent->d_name);
}
else{
printf("\n");
}
} // end of if condition
} // end of while loop
closedir (dir);
}
When you recursively call getFile
you only call it with the only the name of the directory you just read. It's not the full path, which is what you need. You have to manage that yourself.
Something like this:
if(ent->d_type == DT_DIR)
{
if ((strlen(path) + strlen(ent->d_name) + 1) > PATH_MAX)
{
printf("Path to long\n");
return;
}
char fullpath[PATH_MAX + 1];
strcpy(fullpath, path);
strcat(fullpath, "/");
strcat(fullpath, ent->d_name); // corrected
getFile(fullpath);
}
这篇关于递归查找子目录和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!