@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.
@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:
Always remember to handle errors appropriately in the program to ensure graceful execution and error reporting.