如何使用c程序在linux中获得磁盘使用率?

如何使用c程序在linux中获得磁盘使用率?,c,linux,ubuntu-18.04,C,Linux,Ubuntu 18.04,我想在linux中获得磁盘使用率,但当我运行上述代码时,结果是错误的 #include <stdio.h> #include <sys/statvfs.h> int main(int argc, const char *argv[]) { const unsigned int GB = (1024 * 1024) * 1024; struct statvfs buffer; int ret = statvfs("/dev/sda4", &

我想在linux中获得磁盘使用率,但当我运行上述代码时,结果是错误的

#include <stdio.h>
#include <sys/statvfs.h>

int main(int argc, const char *argv[])
{

    const unsigned int GB = (1024 * 1024) * 1024;
    struct statvfs buffer;
    int ret = statvfs("/dev/sda4", &buffer);

    if (!ret) {
        const double total = (double)(buffer.f_blocks * buffer.f_frsize) / GB;
        const double available = (double)(buffer.f_bfree * buffer.f_frsize) / GB;
        const double used = total - available;
        const double usedPercentage = (double)(used / total) * (double)100;
        printf("Total: %f --> %.0f\n", total, total);
        printf("Available: %f --> %.0f\n", available, available);
        printf("Used: %f --> %.1f\n", used, used);
        printf("Used Percentage: %f --> %.0f\n", usedPercentage, usedPercentage);
    }
    return ret;
}
我在linux终端上运行df命令。输出为:

Total: 7.757446 --> 8
Available: 7.757446 --> 8
Used: 0.000000 --> 0.0
Used Percentage: 0.000000 --> 0
Filesystem       1K-blocks    Used  Available   Use% Mounted on      
**/dev/sda4      471705824 13885152 433789596   4% /**

这两个结果是不同的。原因是什么?

您不能使用设备“/dev/sda4”。您必须使用一个路径,在该路径中设备已像“/”或“/home”一样安装。如果使用设备名称,则会得到“udev”文件系统的结果。

您不能使用设备“/dev/sda4”。您必须使用一个路径,在该路径中设备已像“/”或“/home”一样安装。如果使用设备名,则会得到“udev”文件系统的结果。

可以更改为
constdouble-GB=1024.0*1024*1024
100.0
并删除所有不必要的cast您可以更改为
const double GB=1024.0*1024*1024
100.0
并删除所有不必要的castsRight,我用“/”更改了路径。我需要显示/dev/sda4的磁盘使用情况。但结果也不一样/dev/sda4可用:当我运行“df-h/”命令时为414G。但程序输出是可用的437GB@engineer看看它们之间的区别。你计算GiB,它比GB小。对,我用“/”改变了路径。我需要显示/dev/sda4的磁盘使用情况。但结果也不一样/dev/sda4可用:当我运行“df-h/”命令时为414G。但程序输出是可用的437GB@engineer看看它们之间的区别。您计算GiB,它小于GB。