前兩天工作有需求,需要查詢一個路徑的總空間大小和可用空間大小,結(jié)果就查到了這個函數(shù),測試程序如下:
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里包含的字節(jié)數(shù)
- unsigned long long totalsize = blocksize * diskInfo.f_blocks; //總的字節(jié)數(shù),f_blocks為block的數(shù)目
- 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;
- }
編譯過程,運行結(jié)果,與df命令對比結(jié)果如下:
- 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$
好像有點誤差。
水平有限,如果有朋友發(fā)現(xiàn)錯誤,歡迎留言交流。
轉(zhuǎn)載請保留本文鏈接,如果覺得我的文章能幫到您,請頂一下。,謝謝。
|