Handling 'Disk Full' scenarios
What you'll learn: How to detect when a file write operation fails because the storage device has run out of space.
Imagine you are pouring water into a glass. You don't just keep pouring forever; you watch the rim to ensure the water doesn't overflow. In C programming, writing to a file is similar. You might assume the "glass" (your hard drive or USB stick) is infinite, but eventually, it hits a limit. If your program keeps "pouring" data into a full disk, that data simply disappears into the void, often leaving your files corrupted or incomplete.
The silent failure of fprintf
Many beginners assume that if fopen works, everything else will follow suit. However, fprintf and fputs can fail midway through a program's execution if the disk fills up. To catch this, you must check the return value of your output functions. These functions return a negative value (or EOF) if they fail to write the data.
Using fflush to be sure
C uses a "buffer," which is like a small holding tank for data. When you call fprintf, the data might stay in RAM rather than hitting the disk immediately. To truly know if the disk is full, you should use fflush() or check the return value of fclose(). If the disk is full, the computer won't be able to empty that holding tank onto the physical drive, and it will finally report an error.
Example: Checking for success
Here is how you safely handle a write operation:
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "w");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Attempt to write data
if (fprintf(file, "Important backup data...") < 0) {
printf("Write failed! Disk might be full.\n");
}
// Final check: Does the data actually land on the disk?
if (fclose(file) != 0) {
perror("Error closing file (Disk likely full or hardware error)");
return 1;
}
return 0;
}
By checking the return value of fclose, you catch errors that happened at the very last second when the system tried to commit the remaining buffered data to the hardware.
Key takeaway
Always check the return values of write functions and fclose() to ensure your data actually reached the disk safely.