递归计数给定目录的文件和所有目录
Recursively counting files and all directories given the directory
我一直在做这个项目,但我被这段代码中的一行卡住了。
这基本上是通过在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 ®, 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
中名称的内容,你需要创建自己的本地副本并使用它。
相关文章:
- 递归计数给定目录的文件和所有目录
- 包含模板文件的递归会导致编译失败
- 递归地将FEATURE_FLAG导出到生成文件、CPP 和头文件
- 如何递归复制文件和目录
- 使用FindFirstFile和FindNextFile递归查找具有特定扩展名的文件
- boost::文件系统递归获取每个文件的大小
- C++ 源代码的递归生成文件
- 问题 - 递归函数以返回文本文件排列
- 使用C 列出目录中的文件,而不是递归,只有文件和无子目录
- 列出MFC错误中递归运行的所有文件
- 同一生成文件中的 make 目标之间的递归依赖关系
- 递归递归文件
- 递归扫描目录中的文件
- 使用boost递归地将给定目录中每个最低级别文件夹的文件复制到另一个目录-C++
- 输入所有子文件夹 - 递归
- 用于列出子目录中所有文件的递归功能
- 使用递归获取某个目录中的所有文件
- Qt vs Boost 文件系统递归文件计数
- 如何用C++递归地从二进制文件中读取自定义字符串
- 在Qt中递归浏览目录,跳过文件夹"."并".."