我在第二次调用时打开相同的目录时遇到问题。 例如,我首先打开文件夹 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/