http://blog.csdn.net/wzzfeitian/article/details/7825225
前两天工作有需求,需要查询一个路径的总空间大小和可用空间大小,结果就查到了这个函数,测试程序如下:
test.c
- <span style="font-family:Microsoft YaHei;font-size:18px;">#include <sys/statfs.h>
- #include <stdio.h>
- int main()
- {
- struct statfs diskInfo;
- statfs("/home/carl/", &diskInfo);
- unsigned long long blocksize = diskInfo.f_bsize; //每个block里包含的字节数
- unsigned long long totalsize = blocksize * diskInfo.f_blocks; //总的字节数,f_blocks为block的数目
- printf("Total_size = %llu B = %llu KB = %llu MB = %llu GB\n",
- totalsize, totalsize>>10, totalsize>>20, totalsize>>30);
- unsigned long long freeDisk = diskInfo.f_bfree * blocksize; //剩余空间的大小
- unsigned long long availableDisk = diskInfo.f_bavail * blocksize; //可用空间大小
- printf("Disk_free = %llu MB = %llu GB\nDisk_available = %llu MB = %llu GB\n",
- freeDisk>>20, freeDisk>>30, availableDisk>>20, availableDisk>>30);
- return 0;
- }</span>
编译过程,运行结果,与df命令对比结果如下:
- <span style="font-family:Microsoft YaHei;font-size:18px;">carl@carl-VirtualBox:~/share$ gcc test.c -o test_statfs
- carl@carl-VirtualBox:~/share$ ./test_statfs
- Total_size = 20332810240 B = 19856260 KB = 19390 MB = 18 GB
- Disk_free = 15492 MB = 15 GB
- Disk_available = 14519 MB = 14 GB
- carl@carl-VirtualBox:~/share$ df /home/carl -h
- Filesystem Size Used Avail Use% Mounted on
- /dev/sda1 19G 3.9G 15G 22% /
- carl@carl-VirtualBox:~/share$
- </span>
好像有点误差。
水平有限,如果有朋友发现错误,欢迎留言交流。
转载请保留本文链接,如果觉得我的文章能帮到您,请顶一下。,谢谢。