无法再次打开目录

标签 c directory

我在第二次调用时打开相同的目录时遇到问题。 例如,我首先打开文件夹 1/文件夹 2;然后,如果我调用我在 folder1 上使用的函数,它会说无法打开它。我虽然会关闭路径中的所有目录并尝试这样做但没有结果。 这是我的代码

void scanDir(char *dir, int depth, char type, char *path, long gtsize, int attrib)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;
    char newPath[strlen(path)+strlen(dir)];
    if((dp = opendir(dir)) == NULL) {
        fprintf(stderr,"Cannot open directory %s\n because of e", dir);
        exit(10);
        return;
    }
    strcpy(newPath, path);
    strcat(newPath, dir);
    if (type!='f' && testAttrib(attrib, dir))
        printf("%s\n", newPath); 
    strcat(newPath, "/");
    chdir(dir);
    while((entry = readdir(dp)) != NULL) {
        stat(entry->d_name,&statbuf);

        if(S_ISDIR(statbuf.st_mode) && testAttrib(attrib, entry->d_name)) {
            if(!strcmp(".",entry->d_name) || !strcmp("..",entry->d_name))
               continue; // ignore . and ..
            if (depth>1 || depth<=-1)
                scanDir(entry->d_name,depth-1,type,newPath,gtsize,attrib);
        }
        if(S_ISREG(statbuf.st_mode) && type!='d' && testAttrib(attrib, entry->d_name)) {
                off_t sizeF = statbuf.st_size;
                char filePath[100];
                strcpy(filePath, newPath);
                strcat(filePath, entry->d_name);
                if(sizeF>=gtsize)
                    printf("%s \n", filePath);
            }
    }
    chdir("..");
    closedir(dp);
}

最佳答案

char newPath[strlen(path)+strlen(dir)];  //WRONG!

肯定是错的。您需要为终止 0 保留一个额外的字节,并且您正在添加 /。所以应该是

char newPath[strlen(path)+strlen(dir)+2];

顺便说一句,考虑使用 snprintf(3)asprintf(3)而不是您的 strcat 调用。

我不确定调用 chdir(2)是个明智的主意,您当然应该检查它是否运行良好。参见 perror(3) , errno(3) , strerror(3) .

另请查看 nftw(3) .

关于无法再次打开目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44280263/

相关文章:

c - 如果我可以通过 C 中的指针修改它,那么 const 限定符的目的是什么?

c - 如何获取集合的所有可能的子集

c++ - 如何在标准 C/C++ :/or\? 中获取文件分隔符

c# - 在 Directory.GetFiles() 中停止隐式通配符

python - 使用 glob 的多个文件扩展名来查找文件

c++ - 在多线程环境中什么会导致 "bad file descriptor"?

c++ - 如何复制 const char* 类型变量的内容?

python - 查找子目录路径的最有效方法

php - PHP 中的 Linux 文件夹标识或元数据

windows - 目录打印工具?