Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can get disk usage in linux using c program?

I want to get disk usage in linux but when I run above code, the result is wrong.

#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;
}

The output is:

Total: 7.757446 --> 8
Available: 7.757446 --> 8
Used: 0.000000 --> 0.0
Used Percentage: 0.000000 --> 0

I run df command in linux terminal. The output is:

Filesystem       1K-blocks    Used  Available   Use% Mounted on      
**/dev/sda4      471705824 13885152 433789596   4% /**

These two result is different from each other. What is the reason?

like image 500
engineer Avatar asked Jun 24 '26 23:06

engineer


1 Answers

You can not use the device "/dev/sda4". You have to use a path, where the device has been mounted like "/" or "/home". If you use the device name, you get the result for the "udev" filesystem.

like image 51
ceving Avatar answered Jun 27 '26 12:06

ceving



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!