How can get disk usage in linux using c program?

by keegan.towne , in category: General Help , 7 months ago

How can get disk usage in linux using c program?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by benny_schoen , 6 months ago

@keegan.towne 

You can get the disk usage in Linux using a C program by utilizing the statvfs() system call to retrieve information about a filesystem.


Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>
#include <stdlib.h>
#include <sys/statvfs.h>

int main() {
    struct statvfs stats;

    // Path to the filesystem you want to check
    char* path = "/";

    if (statvfs(path, &stats) == -1) {
        perror("Error getting disk usage");
        exit(EXIT_FAILURE);
    }

    // Total available space in bytes
    unsigned long long total_space = stats.f_blocks * stats.f_frsize;

    // Free space in bytes
    unsigned long long free_space = stats.f_bfree * stats.f_frsize;

    // Used space in bytes
    unsigned long long used_space = total_space - free_space;

    // Disk usage percentage
    double disk_usage = (double)used_space / total_space * 100;

    printf("Total space: %llu bytes
", total_space);
    printf("Free space: %llu bytes
", free_space);
    printf("Used space: %llu bytes
", used_space);
    printf("Disk usage: %.2f%%
", disk_usage);

    return 0;
}


You can modify the path variable to specify the filesystem path you want to check. This code will print the total available space, free space, used space, and disk usage percentage.

by bobbie.kris , 2 months ago

@keegan.towne 

The provided C program snippet uses the statvfs() system call to retrieve information about a filesystem and calculates the disk usage accordingly. It offers insights into the total available space, free space, used space, and disk usage percentage.


To run the program:

  1. Save the code snippet in a file, e.g., disk_usage.c.
  2. Compile the program using a C compiler, such as gcc. gcc disk_usage.c -o disk_usage
  3. Execute the compiled binary to get the disk usage information. ./disk_usage
  4. The program should output details about the disk usage on the specified filesystem path (in this case, /).


Always remember to handle errors appropriately in the program to ensure graceful execution and error reporting.