Skip to main content
almarefa.net

Back to all posts

How to Get Disk Usage In Linux Using the C Program?

Published on
6 min read
How to Get Disk Usage In Linux Using the C Program? image

Best Linux Disk Monitoring Tools to Buy in October 2025

1 DASBET 4 Pack Brake Lining Thickness Gauge, 8 Piece Brake Pad Measuring Tool Color Coded with Metric & SAE Size for Measuring Disc & Drum Brake Pad Gauge 2mm to 12mm

DASBET 4 Pack Brake Lining Thickness Gauge, 8 Piece Brake Pad Measuring Tool Color Coded with Metric & SAE Size for Measuring Disc & Drum Brake Pad Gauge 2mm to 12mm

  • ENSURE VEHICLE SAFETY WITH QUICK AND ACCURATE BRAKE MEASUREMENTS.
  • COLOR-CODED GAUGES FOR EASY IDENTIFICATION OF BRAKE HEALTH STATUS.
  • DURABLE STEEL DESIGN GUARANTEES LONG-LASTING, RELIABLE PERFORMANCE.
BUY & SAVE
$14.99
DASBET 4 Pack Brake Lining Thickness Gauge, 8 Piece Brake Pad Measuring Tool Color Coded with Metric & SAE Size for Measuring Disc & Drum Brake Pad Gauge 2mm to 12mm
2 United Scientific™ SCDSK1 Plastic Secchi Disk

United Scientific™ SCDSK1 Plastic Secchi Disk

  • ACCURATE WATER CLARITY MEASUREMENT WITH EASY-TO-READ DESIGN.
  • DURABLE CONSTRUCTION ENSURES LONG-LASTING AND RELIABLE USE.
  • CONVENIENT 72-FOOT LINE WITH CLEAR FOOT MARKINGS FOR PRECISION.
BUY & SAVE
$28.56
United Scientific™ SCDSK1 Plastic Secchi Disk
3 Mobile Fidelity Sound Lab - Geo-Disc Cartridge Alignment Tool - MOFI MFSL

Mobile Fidelity Sound Lab - Geo-Disc Cartridge Alignment Tool - MOFI MFSL

  • EFFORTLESS CARTRIDGE SETUP FOR QUICK AND PRECISE ALIGNMENT.
  • USER-FRIENDLY DESIGN ENSURES ACCURATE ALIGNMENT EVERY TIME.
  • SIMPLY PLACE ON PLATTER AND ALIGN USING PRINTED GRAPH.
BUY & SAVE
$59.94
Mobile Fidelity Sound Lab - Geo-Disc Cartridge Alignment Tool - MOFI MFSL
4 Performance Tool W16500 Professional DEF Tester (Disc Type DEF, Diesel Exhaust Fluid tester)

Performance Tool W16500 Professional DEF Tester (Disc Type DEF, Diesel Exhaust Fluid tester)

  • ACCURATE DEF PURITY READINGS IN ANY TEMPERATURE CONDITION.
  • COMPATIBLE WITH MOST DIESEL VEHICLES FROM 2010 ONWARD.
  • SIMPLE DESIGN FOR EASY MONITORING OF DEF LEVELS AT HOME.
BUY & SAVE
$15.69 $19.99
Save 22%
Performance Tool W16500 Professional DEF Tester (Disc Type DEF, Diesel Exhaust Fluid tester)
5 Brake Pad Measuring Tools, Combination Brake Pad Thickness Gauge 8-Piece Set SAE & Metric 2-12mm Brake Lining Measurement for Cars Automotive Disc and Drum Brake Measure Ruler Tool

Brake Pad Measuring Tools, Combination Brake Pad Thickness Gauge 8-Piece Set SAE & Metric 2-12mm Brake Lining Measurement for Cars Automotive Disc and Drum Brake Measure Ruler Tool

  • QUICK & ACCURATE MEASUREMENTS: EFFORTLESSLY MONITOR BRAKE PAD THICKNESS.
  • DURABLE CONSTRUCTION: STRONG, LIGHTWEIGHT DESIGN FOR LASTING PERFORMANCE.
  • COLOR-CODED ALERTS: EASILY IDENTIFY WHEN BRAKE PADS NEED REPLACING.
BUY & SAVE
$5.99
Brake Pad Measuring Tools, Combination Brake Pad Thickness Gauge 8-Piece Set SAE & Metric 2-12mm Brake Lining Measurement for Cars Automotive Disc and Drum Brake Measure Ruler Tool
6 StarTech.com 4 Bay SSD/HDD Hard Drive Eraser, 2.5/3.5" SATA, Hostless Standalone Secure Erase, Disk Sanitizer, Hardware Wiper Erasing Tool, 9 Modes, RS232 Printer Port, NIST/DOD, LCD, TAA (SATERASER4)

StarTech.com 4 Bay SSD/HDD Hard Drive Eraser, 2.5/3.5" SATA, Hostless Standalone Secure Erase, Disk Sanitizer, Hardware Wiper Erasing Tool, 9 Modes, RS232 Printer Port, NIST/DOD, LCD, TAA (SATERASER4)

  • ERASE UP TO 4 DRIVES SIMULTANEOUSLY-FAST AND EFFICIENT HARD DRIVE MANAGEMENT.

  • 9 ERASE MODES ENSURE COMPLIANCE WITH NIST AND FUTURE DOD STANDARDS.

  • LCD DISPLAY & PRINTED CONFIRMATIONS PROVIDE EASY TRACKING OF ERASE STATUS.

BUY & SAVE
$626.99
StarTech.com 4 Bay SSD/HDD Hard Drive Eraser, 2.5/3.5" SATA, Hostless Standalone Secure Erase, Disk Sanitizer, Hardware Wiper Erasing Tool, 9 Modes, RS232 Printer Port, NIST/DOD, LCD, TAA (SATERASER4)
+
ONE MORE?

To get the disk usage in Linux using a C program, you can follow these steps:

  1. Include the necessary header files: #include #include
  2. Declare the main function: int main() {
  3. Declare the required variables: struct statvfs stat; unsigned long totalSpace, freeSpace, usedSpace; const char* mountPoint = "/"; // Specify the mount point according to your requirement
  4. Use the statvfs function to retrieve the disk usage information: if (statvfs(mountPoint, &stat) == 0) { totalSpace = stat.f_blocks * stat.f_bsize; freeSpace = stat.f_bfree * stat.f_bsize; usedSpace = totalSpace - freeSpace; printf("Total space: %lu bytes\n", totalSpace); printf("Free space: %lu bytes\n", freeSpace); printf("Used space: %lu bytes\n", usedSpace); } else { printf("Failed to retrieve disk usage information.\n"); }
  5. Close the main function: return 0; }

In this program, the statvfs function retrieves information about the filesystem containing the specified mountPoint. Using the obtained data, you can calculate the total disk space, free space, and used space in bytes.

Note: Make sure to compile the C program using a C compiler before running it in the Linux environment.

How to implement a disk space alert system based on usage thresholds using C programming in Linux?

To implement a disk space alert system based on usage thresholds using C programming in Linux, you can follow these steps:

  1. Include the required header files:

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

  1. Define the thresholds for disk space usage in percentages:

#define THRESHOLD_WARNING 80 #define THRESHOLD_ALERT 90

  1. Create a function to check the disk space and compare it with the thresholds:

void checkDiskSpace() { struct statvfs stat;

// Get disk space information for the root directory
if (statvfs("/", &stat) == -1) {
    fprintf(stderr, "Error getting disk space information\\n");
    return;
}

// Calculate the free space in percentage
float freeSpace = (float)(stat.f\_bavail \* stat.f\_frsize) / (float)(stat.f\_blocks \* stat.f\_frsize) \* 100;

// Check if the free space crossed the warning threshold
if (freeSpace < THRESHOLD\_WARNING) {
    printf("WARNING: Disk space is running low - %.2f%% free\\n", freeSpace);
}

// Check if the free space crossed the alert threshold
if (freeSpace < THRESHOLD\_ALERT) {
    printf("ALERT: Disk space is critically low - %.2f%% free\\n", freeSpace);
}

}

  1. Create a main function to schedule the disk space check periodically:

int main() { while (1) { checkDiskSpace();

    // Delay for 1 hour before checking again
    sleep(3600);
}

return 0;

}

  1. Compile the program using GCC:

gcc -o disk_space_alert disk_space_alert.c

  1. Run the program:

./disk_space_alert

This program will periodically check the disk space and print warnings or alerts based on the thresholds defined. Adjust the thresholds as per your requirements and modify the warning and alert messages as needed.

How to programmatically retrieve the disk usage information of remote machines in Linux using C?

To retrieve the disk usage information of remote machines in Linux using C, you can use the following steps:

  1. Make sure you have the necessary permissions to access the remote machine. Typically, this involves setting up SSH access and ensuring that the necessary credentials are available.
  2. Establish an SSH connection to the remote machine. You can use the libssh library in C to achieve this. To install libssh, use the command sudo apt-get install libssh-dev on Ubuntu or equivalent for your Linux distribution.
  3. After establishing the SSH connection, you can use the df command to retrieve disk usage information. You can use the popen function in C to execute the df -h command on the remote machine. The -h option is used to display the result in human-readable format.

Here's an example code snippet that demonstrates the above steps:

#include <stdio.h> #include <stdlib.h>

int main() { FILE* pipe; char buffer[128]; char command[] = "ssh @ \"df -h\"";

pipe = popen(command, "r");
if (pipe == NULL) {
    printf("Error executing command.\\n");
    return 1;
}

while (fgets(buffer, sizeof(buffer), pipe) != NULL) {
    printf("%s", buffer);
}

pclose(pipe);
return 0;

}

Make sure to replace <remote-machine-username> and <remote-machine-ip> with the appropriate values for your remote machine. Compile and run the above code, and it will execute the df -h command on the remote machine and display the result.

Note that this is just a basic example, and you may need to handle error cases, customize the code according to your requirements, and handle other specific scenarios depending on your use case.

What is the command to check the disk usage of a specific file in Linux using C?

To check the disk usage of a specific file in Linux using C, you can use the stat() system call. Here is an example code snippet:

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

int main() { char filename[] = "/path/to/file"; // specify the file path you want to check

struct stat file\_stat;
if (stat(filename, &file\_stat) == 0) {
    printf("File size: %ld bytes\\n", file\_stat.st\_size);
} else {
    printf("Error: Unable to get file stats.\\n");
}

return 0;

}

Please replace /path/to/file with the actual path of the file you want to check. The above code retrieves the file statistics using stat() and prints the file size in bytes.

What is the difference between disk usage and memory usage in Linux?

The difference between disk usage and memory usage in Linux is as follows:

  1. Disk Usage: Disk usage refers to the amount of storage space that is being utilized on a hard disk or other storage devices. It represents the total amount of data stored on the disk, including the operating system, programs, files, and folders. Disk usage is typically measured in bytes, kilobytes (KB), megabytes (MB), gigabytes (GB), or terabytes (TB). Monitoring disk usage is important to ensure that the storage capacity is not exceeded and to manage disk space effectively.
  2. Memory Usage: Memory usage, also known as RAM (Random Access Memory) usage, refers to the amount of memory being utilized by running processes in a computer's physical memory. It represents the temporary storage space that is actively being used by the operating system and applications. Memory usage is typically measured in bytes, kilobytes (KB), megabytes (MB), or gigabytes (GB). Monitoring memory usage is important to ensure that the system has enough available memory for smooth performance and to detect any memory-intensive processes that could lead to system slowdowns or crashes.

In summary, disk usage refers to the storage space used on a hard disk or storage device, while memory usage refers to the amount of physical memory being used by running processes.