C程序文件/文件夹搜索重复

时间:2017-01-05 15:29:42

标签: c

我的程序只循环浏览1个文件夹。当我运行它时,程序输出文件夹1文件夹的名称,而不是输入它并列出其文件。

void getFilesInDirectory(char *loc){
struct dirent *dirp;
DIR *rec;
struct stat f_info;
char full[PATH_MAX + 1];

rec = opendir(loc);
while ((dirp = readdir(rec)) != NULL)
{
    if(strcmp(dirp->d_name,".") != 0 && strcmp(dirp->d_name,"..") != 0){
        stat(dirp->d_name, &f_info);
        _fullpath(full, dirp->d_name, PATH_MAX);

        if(S_ISDIR(f_info.st_mode)){
            getFilesInDirectory(full);
        }else{
            printf("%s\n", dirp->d_name);
        }
    }
}
close(rec);
}

输出:

file1.txt
file2.txt
folder1
folder2

文件夹1和文件夹2分别是file3.txt和file4.txt,但程序没有列出它们。所以我的输出应该是

file1.txt
file2.txt
file3.txt
file4.txt

是否存在递归停止1个文件夹深度的原因

1 个答案:

答案 0 :(得分:1)

问题是您使用错误的文件名调用stat()。你需要传递完整的文件名 - 它不知道你在查看“loc”目录中的文件。

sprintf(full,"%s/%s",loc,dirp->d_name);
stat(full, &f_info);

我也看不到你的_fullpath函数如何工作,因为你没有传递它loc