我想通过C程序获取linux中特定目录的确切大小.我尝试使用statfs(path,struct statfs&)但它没有给出确切的大小.我也尝试过stat()但是对于任何一个dir,它返回大小为4096!
请建议我通过"du -sh dirPath"命令得到dir的确切大小的方式.
另外,我不想通过系统()使用du.
提前致谢.
典型解决方案
如果你想要一个目录的大小,类似于du的方式,创建一个递归函数.迭代地解决问题是可能的,但解决方案有助于递归.
信息
这是一个帮助您入门的链接:
http://www.cs.utk.edu/~plank/plank/classes/cs360/360/notes/Prsize/lecture.html
搜索
使用'stat c program recursive directory size'搜索Google
例
直接来自Jim Plank的网站,作为一个例子来帮助您入门.
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
main()
{
DIR *d;
struct dirent *de;
struct stat buf;
int exists;
int total_size;
d = opendir(".");
if (d == NULL) {
perror("prsize");
exit(1);
}
total_size = 0;
for (de = readdir(d); de != NULL; de = readdir(d)) {
exists = stat(de->d_name, &buf);
if (exists < 0) {
fprintf(stderr, "Couldn't stat %s\n", de->d_name);
} else {
total_size += buf.st_size;
}
}
closedir(d);
printf("%d\n", total_size);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12445 次 |
| 最近记录: |