如何在linux中以程序方式获取一个目录的大小? [英] how to get the size of a dir programatically in linux?
问题描述
我尝试使用statfs(path,struct statfs&),但它没有给出确切的大小。
我也尝试过stat(),但它返回的大小为4096任何dir!
请建议我的方式,我可以得到确切的大小dir就像我们得到du -sh dirPath命令一样。
另外我也不想通过system()使用du。
提前感谢
典型解决方案
如果您想要一个目录的大小,与时尚类似,请创建一个递归函数。有可能迭代地解决这个问题,但解决方案本身就是递归的。
信息
这是一个链接,让您开始:
http://www.cs.utk.edu/~plank/plank/classes/cs360/360/notes/Prsize/lecture .html
搜索
示例
直接来自Jim Plank的网站,如一个例子让你开始。
#include< stdio.h>
#include< dirent.h>
#include< sys / stat.h>
main()
{
DIR * d;
struct dirent * de;
struct stat buf;
int存在;
int total_size;
d = opendir();
if(d == NULL){
perror(prsize);
exit(1);
}
total_size = 0; (de = readdir(d); de!= NULL; de = readdir(d)){
exists = stat(de> d_name,& buf);
if(exists< 0){
fprintf(stderr,can not stat%s\\\
,de> d_name);
} else {
total_size + = buf.st_size;
}
}
closedir(d);
printf(%d\\\
,total_size);
}
I want to get the exact size of a particular dir in linux through a C program. I tried using statfs(path,struct statfs &) but it doesn't give exact size. I also tried with stat() but it returns size as 4096 for any dir !
Please suggest me the way through which I can get the exact size of dir just like we get after "du -sh dirPath" command.
Also I dont wanna use du through system().
Thanks in advance.
Typical Solution
If you want the size of a directory, similar in fashion to du, create a recursive function. It is possible to solve the problem iteratively, but the solution lends itself to recursion.
Information
Here is a link to get you started:
http://www.cs.utk.edu/~plank/plank/classes/cs360/360/notes/Prsize/lecture.html
Search
Search Google with 'stat c program recursive directory size'
Example
Directly from Jim Plank's website, serving as an example to get you started.
#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);
}
这篇关于如何在linux中以程序方式获取一个目录的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!