In C programming, stream error functions are used to detect and handle errors that occur during file operations like reading, writing, or opening a file.
Whenever you work with files using streams (FILE *), there’s always a chance something might go wrong:
- The file might not exist.
- The disk might be full.
- You might try to read beyond the end of the file.
- You might not have the right permissions.
C provides special stream error checking functions to help you find out if such problems occur.
Common Stream Error Functions in C
Here are the most commonly used stream error functions in C:
Function | Purpose |
---|---|
ferror() | Checks for file stream errors |
feof() | Checks if end-of-file is reached |
clearerr() | Resets file error and EOF flags |
perror() | Displays detailed error message |
ferror() Function in C
Checks if an error occurred during a file operation.
Syntax:
int ferror(FILE *stream);
- Non-zero if an error has occurred.
- 0 if no error.
Example:
#include <stdio.h> int main() { FILE *quiz = fopen("sanfoundryquiz.txt", "r"); if (ferror(quiz)) { printf("Error reading file.\n"); } return 0; }
This C program attempts to open sanfoundryquiz.txt for reading. It uses ferror() to check for any errors with the file. If an error occurs, it prints “Error reading file”. However, it doesn’t first verify if the file opened successfully, which can lead to issues.
feof() Function in C
Checks whether the end-of-file indicator is set for a stream.
Syntax:
int feof(FILE *stream);
- Non-zero if end-of-file has been reached.
- 0 otherwise.
Example:
#include <stdio.h> int main() { FILE *test = fopen("sanfoundry.txt", "r"); char ch; while ((ch = fgetc(test)) != EOF) { putchar(ch); } if (feof(test)) { printf("\nEnd of file reached.\n"); } fclose(test); return 0; }
This C program opens sanfoundry.txt for reading. It reads the file character by character using fgetc() and prints each character using putchar(). The loop continues until it reaches the end of the file (EOF). Once the end is reached, feof() checks if the file pointer is at EOF and prints “End of file reached”. Finally, the program closes the file.
clearerr() Function in C
Clears the end-of-file and error indicators for a stream.
Syntax:
void clearerr(FILE *stream);
Example:
#include <stdio.h> int main() { FILE *cert = fopen("empty.txt", "r"); fgetc(cert); // Try to read (may hit EOF) if (feof(cert)) { printf("EOF was reached. Clearing...\n"); clearerr(cert); } fclose(cert); return 0; }
This C program attempts to open empty.txt for reading. It tries to read a character with fgetc(), which may hit the end of the file (EOF). If EOF is reached, feof() checks this and prints “EOF was reached. Clearing…”. The program then calls clearerr(cert) to reset the EOF flag. Finally, it closes the file.
perror() and strerror() Function in C
perror() displays a custom message followed by a colon (:) and the textual representation of the current error (errno).
Syntax:
void perror(const char *str);
- Prints: str: <error message>
- Uses errno internally to show the system-defined error.
strerror() in C
strerror() returns a pointer to the textual description of an error code (usually from errno).
Syntax:
#include <string.h> char *strerror(int errnum);
You manually format the output using printf() or any other display method.
Example of perror() and strerror():
#include <stdio.h> #include <string.h> #include <errno.h> int main() { FILE *quizFile = fopen("sanfoundry_quiz.txt", "r"); if (quizFile == NULL) { // Using perror() perror("Quiz Load Error"); // Using strerror() printf("Quiz Load Error (strerror): %s\n", strerror(errno)); } return 0; }
Sample Output (if file doesn’t exist):
Quiz Load Error: No such file or directory Quiz Load Error (strerror): No such file or directory
This C program tries to open sanfoundry_quiz.txt in read mode. If the file can’t be opened, it prints two error messages. First, it uses perror() to show a message with system error details. Then it uses strerror(errno) to print the same error in a more customizable way. Both help in understanding why the file failed to open.
Common Scenarios and Error Handling Techniques
Scenario 1: File Not Found
Issue: Attempting to open a non-existent file.
Solution:
FILE *fp = fopen("nonexistent.txt", "r"); if (fp == NULL) { perror("File not found"); return 1; }
Always check the return value of fopen() to ensure the file was opened successfully.
Scenario 2: Reading Past EOF
Issue: Continuing to read after reaching the end of the file.
Solution:
int ch; while ((ch = fgetc(fp)) != EOF) { // Process character } if (feof(fp)) { printf("Reached end of file.\n"); }
Use feof() to detect EOF and prevent unnecessary read attempts.
Scenario 3: Write Error Due to Disk Full
Issue: Disk is full during a write operation.
Solution:
FILE *fp = fopen("data.txt", "w"); if (fp == NULL) { perror("Error opening file"); return 1; } if (fprintf(fp, "Data") < 0) { if (ferror(fp)) { perror("Write error"); } } fclose(fp);
Check the return value of write operations and use ferror() to detect write errors.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Practice BCA MCQs
- Apply for C Internship
- Practice Computer Science MCQs
- Check C Books
- Check Computer Science Books