engineer
engineer

Reputation: 93

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?

Upvotes: 3

Views: 4582

Answers (1)

ceving
ceving

Reputation: 23774

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.

Upvotes: 5

Related Questions