how to check file pointers in c
Certainly! In C, you can check file pointers by using the feof()
and ferror()
functions. Here's an explanation for each step:
- feof() Function:
feof()
checks for the end-of-file indicator for the given file stream.- It returns a non-zero value (true) if the end-of-file indicator for the file stream is set. Otherwise, it returns 0 (false).
- Syntax:
int feof(FILE *stream);
Example usage:
c FILE *filePointer; // Open file filePointer = fopen("file.txt", "r"); if (filePointer == NULL) { // handle file opening error } else { // Read file content while (!feof(filePointer)) { // Read file content } // Check end-of-file indicator if (feof(filePointer)) { // End-of-file reached } }
ferror() Function:
ferror()
checks if an error has occurred on the given file stream.- It returns a non-zero value (true) if an error indicator is set for the file stream. Otherwise, it returns 0 (false).
- Syntax:
int ferror(FILE *stream);
- Example usage:
c FILE *filePointer; // Open file filePointer = fopen("file.txt", "r"); if (filePointer == NULL) { // handle file opening error } else { // Read file content while (!feof(filePointer)) { // Read file content } // Check for errors if (ferror(filePointer)) { // An error occurred while reading the file } }
Remember, after opening a file, it's essential to check if the file pointer is not NULL, indicating a successful file open operation, before performing any read/write operations.