【发布时间】:2023-11-06 21:08:01
【问题描述】:
我编写了一个函数来计算目录中和目录下的文件数(包括子目录中的文件)。 但是,当我在具有子目录的目录上测试代码时,它总是报告错误说:“无法打开目录:没有这样的文件或目录”。 有什么办法可以让它发挥作用吗?
int countfiles(char *root, bool a_flag)//a_flag decide if it including hidden file
{
DIR *dir;
struct dirent * ptr;
int total = 0;
char path[MAXPATHLEN];
dir = opendir(root); //open root dirctory
if(dir == NULL)
{
perror("fail to open dir");
exit(1);
}
errno = 0;
while((ptr = readdir(dir)) != NULL)
{
//read every entry in dir
//skip ".." and "."
if(strcmp(ptr->d_name,".") == 0 || strcmp(ptr->d_name,"..") == 0)
{
continue;
}
//If it is a directory, recurse
if(ptr->d_type == DT_DIR)
{
sprintf(path,"%s%s/",root,ptr->d_name);
//printf("%s/n",path);
total += countfiles(path, a_flag);
}
if(ptr->d_type == DT_REG)
{
if(a_flag == 1){
total++;
}
else if (a_flag == 0){
if (isHidden(ptr->d_name) == 0){
total++;
}
}
}
}
if(errno != 0)
{
printf("fail to read dir");
exit(1);
}
closedir(dir);
return total;
}
【问题讨论】:
-
如果你取消注释
//printf("%s/n",path);这行会显示什么? -
打印 dir 和 ls 的简单案例的结果,并与您的调试输出进行比较。您是否尝试将文件作为目录打开?您是否要打开不完整的路径?这里有很多可能的新手错误