Error Handling During File Operations in C
Last Updated :
13 May, 2025
File operations are a common task in C programming, but they can encounter various errors that need to be handled gracefully. Proper error handling ensures that your program can handle unexpected situations, such as missing files or insufficient permissions, without crashing. In this article, we will learn how to handle some common errors during file operations in C.
Here are some common errors that can occur during file operations:
Error | Cause |
---|
File Not Found | Trying to open a file that doesn’t exist. |
---|
Permission Denied | Insufficient permissions to access the file. |
---|
Disk Full | No space left on the disk for writing data. |
---|
File Already Exists | Attempting to create a file that already exists in w mode. |
---|
Invalid File Pointer | Using a null or invalid file pointer for file operations. |
---|
End-of-File (EOF) | Attempting to read past the end of the file. |
---|
File Not Open | Attempting to perform operations on a file that wasn’t opened successfully. |
---|
Failure to check for errors then the program may behave abnormally therefore an unchecked error may result in premature termination for the program or incorrect output.
Error Handling Techniques
Below are some standard error handling techniques:
1. File Not Found Error
A file not found error can occur when opening a file in read mode (r) or append mode (a). Use fopen() and check for NULL. If it is, the error message can be printed using perror() function.
C
#include <stdio.h>
int main() {
// Try to open file in
// read mode
FILE *file = fopen("file.txt", "r");
// Check if the file
// is opened/found
if (file == NULL) {
perror("Error");
return 1;
}
fclose(file);
return 0;
}
Output
Error: No such file or directory
In the above program, fopen() returns a NULL pointer because the file is not present in the current directory, then the perror() function prints the error message.
2. Handle Permission Denied Error
If the file exists but the program lacks the required permissions, fopen() will fail and return NULL pointer. We can change the perror() output to "permission denied" as shown in the below snippet.
C
FILE *file = fopen("/restricted/file.txt", "w");
if (file == NULL) {
perror("Permission denied");
}
3. Handle Disk Full Error
When writing to a file, ensure the disk has enough space. Errors during file operations can be detected using ferror(). In the below program, we assume that there is no space in memory to store any data.
C
#include <stdio.h>
int main() {
FILE *fptr = fopen("file.txt", "w");
if (fptr == NULL) {
perror("Error opening file");
return 1;
}
fprintf(fptr, "Writing to file");
// Check error after performing
// write operation
if (ferror(fptr)) {
perror("Error writing to file");
}
fclose(fptr);
return 0;
}
Output
Error writing to file: Permission Denied
4. Handle File Already Exists
When creating a new file with fopen() in w mode, the existing file will be overwritten. To avoid this, we open a new file in wx mode because if file is already present then fopen() return NULL and set the EEXIST value to the errno. In the below program, we assume that "test.text" file is already present in current directory.
C
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
FILE *fptr;
// Try to open the file in
// write mode
fptr = fopen("test.text", "wx");
if (fptr == NULL) {
// Check if the error is
// due to file already existing
if (errno == EEXIST)
printf("File already exist");
}
// If we reach here, the file
// was created successfully
fprintf(fptr, "This is a new file.");
fclose(fptr);
return 0;
}
Output
File already exist
5. Handle Invalid File Pointer
Always verify that the file pointer is not NULL before performing operations like reading or writing.
C
FILE *file = NULL;
if (file == NULL) {
printf("Invalid file pointer. File operations cannot proceed.\n");
}
6. Handle End-of-File (EOF)
When we are reading data from a file and the file pointer reaches the end of the file, we can use the feof() function to handle the end of the file.
C
#include <stdio.h>
int main() {
FILE *file = fopen("test.txt", "r");
// Check for eof while reading
char ch;
while ((ch = fgetc(file)) != EOF)
putchar(ch);
// Use feof() to make sure
// EOF occurred or not
if (feof(file))
printf("End of file reached.");
else if (ferror(file))
printf("Error reading the file.");
fclose(file);
return 0;
}
Output
End of file reached.
7. Handle File Not Open
Whenever we attempt to open a file and the file cannot be opened due to some error, the fopen() function returns NULL. We can handle this easily using an if-else statement.
C
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("File could not be opened.\n");
} else {
printf("File opened successfully.\n");
fclose(file);
}
return 0;
}
Output
File could not be opened.
File Closing Error
Sometimes, when we are closing a file using the fclose() function and it fails to close the file due to an error, it returns -1.
C
#include <stdio.h>
int main() {
FILE *fptr = fopen("test.txt", "w");
fprintf(fptr, "Writing to file");
// Check file close properly
if(fclose(fptr) == -1)
printf("File closing error");
else
printf("File closed")
return 0;
}
Output
File closing error
Similar Reads
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
C Programming Language Tutorial
C is a general-purpose, procedural, and middle-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It is also known as the "mother of all programming languages" as it influenced many modern programming languages like C++, Java, Python, and Go. Why learn C?The C la
5 min read
Object Oriented Programming in C++
Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
In C, a variable defined in a function is stored in the stack memory. The requirement of this memory is that it needs to know the size of the data to memory at compile time (before the program runs). Also, once defined, we can neither change the size nor completely delete the memory.To resolve this,
9 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc.Example:C++int number;The above statement declares a variable with name number that can store integer values.C is a statically type language where
5 min read
Vector in C++ STL
C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
Templates in C++
C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
30 OOPs Interview Questions and Answers [2025 Updated]
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
C Arrays
An array in C is a fixed-size collection of similar data items stored in contiguous memory locations. It can be used to store the collection of primitive data types such as int, char, float, etc., as well as derived and user-defined data types such as pointers, structures, etc. Creating an Array in
8 min read