我编写了一小段代码,使用 nftw 系统调用来进行树遍历。
int flags =0;
flags = flags | FTW_MOUNT;
int nopenfd = 10;
if( nftw( argv[1], sum_sizes, nopenfd, flags) == -1 )
return EXIT_FAILURE;
使用此选项,如果目录是挂载点并取消引用符号链接(默认行为),则 nftw 不会扫描目录。
在每个文件 nftw 调用此函数:
/*total_size is the sum of each file/directory/link*/
long long int total_size, total_real_size = 0;
static int sum_sizes(const char *pathname, const struct stat *statbuf, int typeflag, struct FTW *ftwbuf)
{
/*if stat failed on the current file*/
if(typeflag == FTW_NS)
{
printf("No stats (permissions ?) on %s", pathname);
return 0;
}
total_size = total_size + (long long int ) statbuf->st_size;
total_real_size = total_real_size + (long long int ) ( statbuf->st_blocks * 512 );
return 0;
}
所以最后,我显示累积大小:
printf("total size: %lld (%0.2lf K %0.2lf M)\n", total_size, (float)total_size /1024.0, (float)total_size /(1024.0*1024.0));
printf("total real size: %lld (%0.2lf K %0.2lf M)\n", total_real_size, (float)total_real_size /1024.0, (float)total_real_size /(1024.0*1024.0));
当我将值与 du 进行比较时,我有一些差异
time ./scan_dir ~/
====>
total size: 15208413390 (14851966.00 K 14503.87 M)
total real size: 15708553216 (15340384.00 K 14980.84 M)
block size : 4096 / fond. block size : 4096
fs size: 22.7895 G
./scan_dir ~/ 0,03s user 0,24s system 98% cpu 0,277 total
time du -s ~/
15119876 /home/cedlemo/
du -s ~/ 0,07s user 0,22s system 98% cpu 0,287 total
注意:阅读 du 的手册页后,我知道 du 的行为与我的小应用程序 scan_dir 几乎相同(跳过安装点,取消引用符号链接并使用 1024 来计算 Ko 中的值)
似乎在我的应用程序中找到的更接近的值是实际大小(使用的块)的总和,但值并不完全相同。
这种差异的原因可能是什么?我做错了什么?