我想通过 C 程序获取 linux 中特定目录的确切大小。
我尝试使用 statfs(path,struct statfs &) 但它没有给出确切的大小。
我也尝试过 stat() 但它返回任何目录的大小为 4096 !
请建议我如何获取 dir 的确切大小,就像我们在“du -sh dirPath”命令之后得到的那样。
我也不想通过 system() 使用 du。
提前致谢。
基于吉姆·普朗克的example http://web.eecs.utk.edu/%7Ejplank/plank/classes/cs360/360/notes/Prsize/src/prsize3.c让您开始:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int main( int argc, char **argv ) {
DIR *d = opendir( "." );
if( d == NULL ) {
fprintf( stderr, "Cannot open current working directory\n" );
return 1;
}
struct dirent *de;
struct stat buf;
int total_size = 0;
for( de = readdir( d ); de != NULL; de = readdir( d ) ) {
int exists = stat( de->d_name, &buf );
if( exists < 0 ) {
fprintf( stderr, "Cannot read file statistics for %s\n", de->d_name );
} else {
total_size += buf.st_size;
}
}
closedir( d );
printf( "%d\n", total_size );
return 0;
}
给读者的注释、注意事项和问题:
- 这个例子不完整。参见普兰克notes http://www.cs.utk.edu/%7Eplank/plank/classes/cs360/360/notes/Prsize/lecture.html更多细节。
- 如果有锁定的文件会怎样?
- 符号链接是否需要特殊处理(以避免无限循环)?
- 如何输出错误文件的完整路径名?
这个答案是一个起点,而不是一个完整而强大的计算目录大小的程序。如果您需要更多帮助,请阅读源代码du
程序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)