http://blog.csdn.net/wzzfeitian/article/details/7825225
前两天工作有需求,需要查询一个路径的总空间大小和可用空间大小,结果就查到了这个函数,测试程序如下:
test.c
- #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;
- }
#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;
}
编译过程,运行结果,与df命令对比结果如下:
- 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$
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$
好像有点误差。