Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Error Handling During File Operations in C
Next article icon

Error Handling During File Operations in C

Last Updated : 13 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

ErrorCause
File Not FoundTrying to open a file that doesn’t exist.
Permission DeniedInsufficient permissions to access the file.
Disk FullNo space left on the disk for writing data.
File Already ExistsAttempting to create a file that already exists in w mode.
Invalid File PointerUsing a null or invalid file pointer for file operations.
End-of-File (EOF)Attempting to read past the end of the file.
File Not OpenAttempting 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

Next Article
Error Handling During File Operations in C

A

ayushraj2122
Improve
Article Tags :
  • C Programs
  • C++ Programs
  • C Language
  • C++
  • cpp-file-handling
  • C-File Handling
  • File Handling
  • C Error Handling Programs
Practice Tags :
  • CPP

Similar Reads

    Employee Record System in C using File Handling
    Employee Record System is software built to handle the primary housekeeping functions of a company. ERS helps companies keep track of all the employees and their records. It is used to manage the company using a computerized system. This software built to handle the records of employees of any compa
    5 min read
    C File Handling Programs
    C Program to list all files and sub-directories in a directory C Program to count number of lines in a file C Program to print contents of file C Program to copy contents of one file to another file C Program to merge contents of two files into a third file C program to delete a file
    1 min read
    How to Read a File Line by Line in C?
    In C, reading a file line by line is a process that involves opening the file, reading its contents line by line until the end of the file is reached, processing each line as needed, and then closing the file.Reading a File Line by Line in CReading a file line by line is a step by step:1. Opening th
    3 min read
    How to Open and Close a File in C++?
    In C++, we can open a file to perform read and write operations and close it when we are done. This is done with the help of fstream objects that create a stream to the file for input and output. In this article, we will learn how to open and close a file in C++. Open and Close a File in C++ The fst
    2 min read
    How to Get Error Message When ifstream Open Fails in C++?
    In C++, the std::ifstream class is used to open a file for input operations. It associates an input stream to the file. However, due to some reasons, it may be unable to open the requested file. In this article, we will learn how to show an error message when the ifstream class fails to open the fil
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences