c - 计算C中嵌套目录中文件的块大小
问题描述
我一直在尝试以递归方式计算嵌套文件夹中文件的总块大小。我的代码设法获取第一个文件夹中文件的块大小,但无法读取嵌套在当前文件夹中的文件夹中的文件大小。嵌套文件夹中的文件返回的块大小为零。为什么会这样?
int scanDir (char *fstring)
{
char new_dirname[180] = { 0 };
int total_size = 0;
DIR *dir = opendir(fstring);
if(dir == NULL) {
perror("Could not open file\n");
exit(EXIT_FAILURE);
}
struct dirent *filenum;
filenum = readdir(dir);
while(filenum != NULL) {
if (strcmp(filenum->d_name, ".") != 0 && strcmp(filenum->d_name, "..") != 0) {
//Check if file is not a directory
if (filenum->d_type != DT_DIR ) {
//Get the size of the file and add it to total size
struct stat buf;
int res = lstat(filenum->d_name, &buf);
if (res == 0){
total_size += buf.st_blocks;
printf("%s: %ld\n", filenum->d_name, buf.st_blocks);
}
}else {
//If file is a directory
//Add new path name and the /
printf("%s\n", filenum->d_name);
strcat(new_dirname, fstring);
strcat(new_dirname, "/");
strcat(new_dirname, filenum->d_name);
//Add the return value to total size
total_size += scanDir(new_dirname);
//Clear the array for the next iteration.
memset(new_dirname, 0, 180);
}
}
filenum = readdir(dir);
}
closedir(dir);
return (total_size);
}
解决方案
推荐阅读
- c# - 如何使用中继器调试 C# 分页程序
- base64 - 从 Base64 字符串保存 Golang 中的图像
- ansible - 如何从剧本更改 play_hosts
- c# - 使用多线程进行慢速 Ms 互操作
- php - Laravel 刀片中的表单错误。是“class”或“id”还是什么原因?
- excel - 将工作表转换为 PDF 缺少图像
- batch-file - 修改 CSV 文件以在列中添加数字字符
- powershell - MS-Teams ,尝试将图像(存在于本地计算机上)发送到 Teams 频道 webhook url
- c - C 程序:数组示例
- scikit-learn - TimeSeries NLP:将 ARIMA 与 CountVectorizer 结合使用