本文介绍了如何递归浏览文件夹并计算文件总大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图递归浏览目录并打印文件大小,然后最后打印所有文件大小的总和。我无法找出递归地传递给我的函数的内容,并且我的变量total最终还是不正确,非常感谢任何帮助,在此先感谢您。
I am trying to recursively go through my directories and print file size, then at the end print the total of all file size's. I cannot figure out what to pass my function recursively, and my variable total does not end up being correct,any help is greatly appreciated, thanks so much in advance.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
void do_ls(char[]);
int total = 0;
int main(int ac, char *av[])
{
if (ac == 1)
do_ls(".");
else
{
while (--ac) {
printf("%s:\n", *++av);
do_ls(*av);
}
}
}
void do_ls(char dirname[])
{
DIR *dir_ptr;
struct dirent *direntp;
struct stat info;
if ((dir_ptr = opendir(dirname)) == NULL)
fprintf(stderr, "ls01: cannot opern %s\n", dirname);
else
{
while((direntp = readdir(dir_ptr)) != NULL) {
stat(direntp->d_name, &info);
if (S_ISDIR(info.st_mode))
printf("%s\n", direntp->d_name);
//I believe recursion goes here, I tried the following
//do_ls(direntp->d_name);
else
printf("%d %s\n", (int)info.st_size, direntp->d_name);
total += (int)info.st_size;
}
closedir(dir_ptr);
}
printf("Your total is: %d \n", total);
}
推荐答案
在此行:
while((direntp - readdir(dir_ptr)) != NULL)
您应该设置direntp,而不是减去(我认为)。
you should be setting direntp, not subtracting (I assume).
这篇关于如何递归浏览文件夹并计算文件总大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!