Error Handling in File Operations
Files fail in real life: the file doesn't exist, the folder is wrong, you lack permission, the disk is full. A good program notices these problems and reports them clearly, instead of crashing or silently saving nothing.
In this lesson you will learn every error tool C gives you for files: the NULL check, feof, ferror, clearerr, perror, errno and strerror. You will also learn the famous while (!feof(fp)) trap and how to avoid it.
What You Will Learn
- Common reasons file operations fail.
- How to check fopen and other return values.
- feof vs ferror: end of file vs real error.
- How errno, perror and strerror explain an error.
- Why
while (!feof(fp))is wrong. - How to write a robust file function.
Error Handling in File Operations Explained
Exam definition: feof(fp) returns non-zero if the end-of-file indicator is set; ferror(fp) returns non-zero if an error occurred on the stream; clearerr(fp) resets both. When a library call fails it sets the global variable errno (from <errno.h>); perror(msg) prints msg followed by the error description to stderr, and strerror(errno) returns that description as a string.
Memory trick: Reading a file is like a train journey. feof = "did we reach the last station?" (normal). ferror = "did the train break down?" (a problem). errno = the reason code on the delay board, and perror/strerror = the announcer reading it out in words.
Common reasons file operations fail
- File not found (opening with "r").
- Wrong path or folder doesn't exist.
- No permission (read-only file, protected folder).
- Disk full while writing.
- Reading a file opened only for writing (or vice versa).
- Too many files open at once.
Syntax of File Error Functions
#include <stdio.h>
#include <errno.h>
#include <string.h>
int feof(FILE *fp); /* non-zero: end of file reached */
int ferror(FILE *fp); /* non-zero: an error happened */
void clearerr(FILE *fp); /* reset EOF and error indicators */
void perror(const char *msg); /* print "msg: description" to stderr */
char *strerror(int errnum); /* description text for an error number */
extern int errno; /* last error code (set by failing calls) */
FILE *fp = fopen("data.txt", "r");
if (fp == NULL)
{
perror("data.txt"); /* e.g. data.txt: No such file or directory */
return 1;
}
| Function call | Signals failure by returning |
|---|---|
fopen | NULL |
fclose, fputc, fputs, fgetc | EOF |
fgets | NULL |
fprintf | A negative number |
fscanf | Fewer items than expected, or EOF |
fread, fwrite | Fewer items than requested |
fseek / ftell | Non-zero / -1L |
Example 1: Reporting Why fopen Failed
#include <stdio.h>
#include <errno.h>
#include <string.h>
FILE *open_or_report(const char *name, const char *mode)
{
FILE *fp = fopen(name, mode);
if (fp == NULL)
printf("Cannot open '%s' in mode \"%s\": %s\n", name, mode, strerror(errno));
else
printf("Opened '%s' in mode \"%s\"\n", name, mode);
return fp;
}
int main(void)
{
FILE *fp;
fp = open_or_report("missing_file.txt", "r"); /* doesn't exist */
if (fp != NULL)
fclose(fp);
fp = open_or_report("no_such_folder/out.txt", "w"); /* folder missing */
if (fp != NULL)
fclose(fp);
fp = open_or_report("ok.txt", "w"); /* works */
if (fp != NULL)
{
fputs("saved\n", fp);
if (fclose(fp) == EOF)
printf("Error while closing\n");
}
remove("ok.txt");
return 0;
}
Output
Cannot open 'missing_file.txt' in mode "r": No such file or directory Cannot open 'no_such_folder/out.txt' in mode "w": No such file or directory Opened 'ok.txt' in mode "w"
Code Explanation
- When fopen fails, it returns NULL and sets
errnoto a code likeENOENT(no such entry). strerror(errno)turns that code into readable text. The exact wording can differ slightly between systems.perror("missing_file.txt")would print the same message, but to stderr (the error stream), which is the usual choice in real programs.- Even
fclosecan fail (for example, when buffered data can't be written to a full disk), so serious programs check it too.
How feof and ferror Work (and the feof Trap)
The EOF indicator is set only after a read tries to go past the end. It doesn't predict the end in advance. That's why this popular loop is wrong:
/* WRONG: processes the last line twice (or garbage once) */
while (!feof(fp))
{
fgets(line, sizeof line, fp); /* the failing read happens HERE */
printf("%s", line); /* ...but we still print */
}
/* RIGHT: test the read itself */
while (fgets(line, sizeof line, fp) != NULL)
printf("%s", line);
/* AFTER the loop, find out WHY it stopped */
if (ferror(fp))
printf("read error\n");
else if (feof(fp))
printf("reached end of file\n");
Example 2: The feof Trap vs the Right Loop
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("cities.txt", "w");
char city[30];
int count;
if (fp == NULL)
return 1;
fprintf(fp, "Delhi\nMumbai\nChennai\n");
fclose(fp);
fp = fopen("cities.txt", "r");
if (fp == NULL)
return 1;
count = 0; /* wrong way */
while (!feof(fp))
{
if (fscanf(fp, "%29s", city) != 1) /* fails on the last pass... */
;
count++; /* ...but we still count it */
}
printf("while (!feof) counted : %d cities\n", count);
rewind(fp); /* also clears the EOF flag */
count = 0; /* right way */
while (fscanf(fp, "%29s", city) == 1)
count++;
printf("checking fscanf counted : %d cities\n", count);
if (ferror(fp))
printf("Stopped because of an error\n");
else if (feof(fp))
printf("Stopped at end of file (normal)\n");
clearerr(fp);
printf("After clearerr, feof = %d\n", feof(fp) != 0);
fclose(fp);
remove("cities.txt");
return 0;
}
Output
while (!feof) counted : 4 cities checking fscanf counted : 3 cities Stopped at end of file (normal) After clearerr, feof = 0
- After reading "Chennai", the EOF flag is not yet set, so
!feoflets the loop run once more. That extra read fails, but the count still increases: 4 instead of 3. - Testing
fscanf(...) == 1stops at exactly the right moment. - After the loop,
ferrorandfeoftell us why it stopped: error or normal end. clearerr(andrewind) reset the indicators.
Important Points to Remember
- Always check fopen for NULL and other calls' return values.
- feof = end reached; ferror = real error; clearerr resets both.
- EOF flag is set after a failed read, not before.
- Loop on the read function's result, then use feof/ferror to find the reason.
- errno holds the last error code; strerror(errno) gives its text.
- perror(msg) prints "msg: reason" to stderr.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
while (!feof(fp)) | Last item processed twice | Loop on fgets/fscanf/fread result |
| No NULL check after fopen | Crash with a confusing message | Check and report with perror |
| Reading errno when nothing failed | Old, misleading error code | Use errno only right after a failure |
| Ignoring fwrite's return value | Silent data loss (disk full) | Compare with the count requested |
| Generic "Error!" messages | User can't fix the problem | Print the file name and strerror text |
File Error Handling Practice Questions
- What is the difference between feof and ferror?
- What does perror do? Where does it print?
- Why is
while (!feof(fp))a bad loop condition? - Which header declares errno? Which declares strerror?
- Name three reasons fopen can fail.
Show answers
- feof reports that the end of file was reached (normal); ferror reports that a read/write error occurred.
- It prints the given message, a colon and the description of the current errno, to stderr.
- The EOF flag is set only after a read fails, so the loop runs one extra time with no new data.
- errno:
<errno.h>; strerror:<string.h>. - File doesn't exist (for "r"), folder doesn't exist, no permission (also: disk full, too many open files).
Coding Exercise
Write int count_lines(const char *name) that returns the number of lines in a file, or −1 if the file can't be opened (printing the reason with strerror). Test it on a file you create with 4 lines and on a missing file.
Show solution
#include <stdio.h>
#include <errno.h>
#include <string.h>
int count_lines(const char *name)
{
FILE *fp = fopen(name, "r");
int ch, lines = 0;
if (fp == NULL)
{
printf("%s: %s\n", name, strerror(errno));
return -1;
}
while ((ch = fgetc(fp)) != EOF)
if (ch == '\n')
lines++;
if (ferror(fp))
lines = -1;
fclose(fp);
return lines;
}
int main(void)
{
FILE *fp = fopen("four.txt", "w");
if (fp == NULL)
return 1;
fputs("one\ntwo\nthree\nfour\n", fp);
fclose(fp);
printf("four.txt has %d lines\n", count_lines("four.txt"));
printf("result: %d\n", count_lines("nothing_here.txt"));
remove("four.txt");
return 0;
}
four.txt has 4 lines nothing_here.txt: No such file or directory result: -1
Quick Quiz: File Error Handling (MCQ)
-
Which function checks for an error on a stream?
A)
feofB)ferrorC)fcloseD)fflush -
perror prints its message to:
A) stdout B) stderr C) A log file D) stdin
-
The EOF indicator is set:
A) When the file opens B) Before the last byte is read C) After a read tries to go past the end D) Never
-
Function that resets the EOF and error indicators:
A)
resetB)clearerrC)ferrorD)fclose -
strerror(errno)returns:A) The error number B) A description string C) A FILE pointer D) Nothing
Show answers
- B:
ferror. - B: stderr.
- C: after a read tries to go past the end.
- B:
clearerr. - B: a description string.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| fopen failure | Returns NULL, sets errno |
|---|---|
| feof(fp) | Non-zero at end of file |
| ferror(fp) | Non-zero after an error |
| clearerr(fp) | Resets both flags |
| perror(msg) | "msg: reason" to stderr |
| strerror(errno) | Error text (string.h) |
| Correct loop | Test the read call, not feof |
Frequently asked questions
- What is the difference between feof and ferror?
- feof means the end was reached (normal); ferror means an I/O error happened.
- Why is while(!feof(fp)) wrong?
- The EOF flag is set only after a read fails, so the loop runs one extra time.
- What does perror do?
- Prints your message plus the description of errno to stderr.
Remember
- feof = last station; ferror = breakdown; errno = reason code.
- Check every return value.
Next Topic
Next lesson: File Handling Programs in C. You will write complete file programs: copy a file, count words, append and merge files.