递归计数给定目录的文件和所有目录

Recursively counting files and all directories given the directory

本文关键字:文件 递归      更新时间:2023-10-16

我一直在做这个项目,但我被这段代码中的一行卡住了。

这基本上是通过在UNIX环境中使用C++的目录递归地计算文件和目录数量,但每当我进行递归调用时,它都会出现一个错误:

Segmentation fault (core dumped)

我以为是因为我没有检查"."answers"..",但事实并非如此。

递归调用有什么问题吗?

#include <string>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <iostream>
using namespace std;

void cntFile(string it, int &reg, int &der, size_t &size)
{
DIR * dirp;
struct dirent *entry;
struct stat file_stats;
dirp = opendir(it.c_str());
while ((entry = readdir(dirp)) != NULL)
{
if (entry->d_type == DT_REG)
{
reg++;
stat(getcwd(entry->d_name,sizeof(entry->d_name)), &file_stats);
size += (unsigned int) file_stats.st_size;
}
else if (entry->d_type == DT_DIR)
{  
if(string(entry->d_name) != ".." | string(entry->d_name) != ".")
{
string temp;
temp.append(it + entry->d_name + "/");
cntFile(temp, reg, der, size);
}
der++;
}
}
closedir(dirp); 
}
int main (void)
{
int reg = 0;
int der = 0;
size_t size = 0;
string it = "/usr/share/";
cntFile(it, reg, der, size);
printf("The total number of directories in directory is %d n", reg);
printf("The total number of files in directory is %d n", der);
printf("The total number of bytes occupied by all files in directory is %zun", size);
return 0;
}

如何使用readdir及其返回指针的结构存在一个主要问题。

从链接到上面的参考:

应用程序不应修改readdir()的返回值指向的结构,也不应修改结构中指针指向的任何存储区域。

但这正是您对getcwd调用所做的操作,请修改结构成员d_name的内容。

如果你想修改d_name中名称的内容,你需要创建自己的本地副本并使用它。