Table of contents
1.
Introduction
2.
getc() Function in C
2.1.
Parameters
2.2.
Return Value
3.
feof() Function in C
3.1.
Syntax of feof()
3.2.
Return Value
3.3.
Example of feof()
4.
Frequently Asked Questions
4.1.
What happens if I attempt to read from a file after reaching the end of file?
4.2.
Can I use feof() to check for the end of file before reading from a file?
4.3.
What's the difference between getc() and fgetc()?
5.
Conclusion
Last Updated: Nov 29, 2024
Easy

End of File in C

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Whenever you are writing a program, it's important to know how to detect when a file has reached its end. This allows programs to process files efficiently and avoid any unnecessary errors. The end of the file (EOF) is a special marker that indicates there is no more data to be read from a file. This knowledge is very useful when you are dealing with files on a system level, as it ensures we can manage data flows effectively. 

End of File in C

In this article, we'll discuss two main functions in C for working with the end of a file: getc() & feof(). We'll look into their syntax, parameters, and return values with examples.

getc() Function in C

The get () function is used to read a single character from a file. It takes a file pointer as its argument and returns the character read as an unsigned char cast to an int. If the end of the file is reached or an error occurs, get () returns EOF.


The syntax of getc() is:

int getc(FILE *stream);


It takes a single argument, a pointer to the FILE object representing the input stream to read from.

The FILE pointer is usually obtained by calling the fopen() function to open a file in read mode. For example:

FILE *file = fopen("example.txt", "r");
if (file == NULL) {
    printf("Error opening file.\n");
    return 1;
}

int character = getc(file);


In this example, we first open a file named "example.txt" in read mode using fopen(). We check if the file was opened successfully by ensuring the returned FILE pointer is not NULL.

If the file is opened successfully, we can then pass the FILE pointer to getc() to read a single character from the file. The character read is stored in the `character` variable.

Parameters

The getc() function takes a single parameter:

stream: This is a pointer to the FILE object that represents the input stream to read from. It should be a file opened in read mode using the fopen() function or one of the standard input streams (stdin).

Let’s look at a few important points to remember about the stream parameter:

1. The FILE pointer must be valid and opened in read mode. Attempting to read from a file opened in write mode or an invalid FILE pointer will lead to undefined behavior.
 

2. After reading a character using getc(), the file position indicator is advanced to the next character in the file. Subsequent calls to getc() will read the next characters sequentially.
 

3. If the end of the file is reached, getc() will return the special value EOF (end of file) which is typically defined as -1. It's important to check for this value to detect when there are no more characters to read from the file.
 

4. When you're done reading from the file, it's essential to close the file using the fclose() function to free up system resources and ensure proper file handling.

Return Value

The getc() function returns an int value that represents the character read from the file. The possible return values are: 

1. On success, getc() returns the character read as an unsigned char cast to an int. This means that the actual character value is returned, and you can use it directly or store it in a char variable.
 

2. If the end of the file is reached and no more characters can be read, getc() returns the special value EOF. EOF is a constant defined in the <stdio.h> header file and is typically defined as -1.
 

It's crucial to check the return value of getc() to determine if a character was successfully read or if the end of the file was reached. Here's an example of how you can use the return value:

int character;
while ((character = getc(file)) != EOF) {
    // Process the character
    printf("%c", character);
}


In this code, we use a while loop to repeatedly call getc() and read characters from the file. The loop continues until getc() returns EOF, indicating the end of the file. Inside the loop, we can process each character as needed, such as printing it or performing other operations.

feof() Function in C

The feof() function is another useful C function for detecting the end of a file. It checks whether the end-of-file indicator is set for a given file stream.

The feof() function is typically used in conjunction with other file reading functions, such as getc(), to determine when to stop reading from a file.

Syntax of feof()

The syntax of the feof() function is:

int feof(FILE *stream);


It takes a single argument, `stream`, which is a pointer to the FILE object representing the file stream to check for the end-of-file condition.

The FILE pointer should be obtained by opening a file using the fopen() function or by using one of the standard file streams (stdin, stdout, or stderr).

For example: 

FILE *file = fopen("example.txt", "r");
if (file == NULL) {
    printf("Error opening file.\n");
    return 1;
}

// Read characters from the file
int character;
while ((character = getc(file)) != EOF) {
    // Process the character
    printf("%c", character);
}

// Check if the end of file was reached
if (feof(file)) {
    printf("Reached the end of the file.\n");
} else {
    printf("An error occurred while reading the file.\n");
}
fclose(file);


In this example, we open a file named "example.txt" in read mode using fopen(). We then use a while loop to read characters from the file using getc() until EOF is reached.

After the loop, we use feof() to check the end-of-file condition. If feof() returns a non-zero value, it means the end of the file was reached successfully. Otherwise, if feof() returns zero, it indicates that an error occurred during the file reading process.

Finally, we close the file using fclose() to release the associated resources.

Return Value

The feof() function returns an integer value that indicates whether the end-of-file indicator is set for the specified file stream. The possible return values are:

1. If the end-of-file indicator is set (i.e., the end of the file has been reached), feof() returns a non-zero value, typically 1.
 

2. If the end-of-file indicator is not set (i.e., there are still characters to be read or an error occurred), feof() returns zero.
 

It's important to note that feof() should be used in conjunction with other file reading functions, such as getc(), fread(), or fscanf(), to determine when to stop reading from a file.

Let’s discuss an example that shows how the return value of feof() can be used:

int character;
while ((character = getc(file)) != EOF) {
    // Process the character
    printf("%c", character);
}

if (feof(file)) {
    printf("Reached the end of the file.\n");
} else {
    printf("An error occurred while reading the file.\n");
}


In this code, we read characters from the file using getc() in a while loop until EOF is encountered. After the loop, we check the return value of feof() to determine the reason for exiting the loop.

If feof() returns a non-zero value, it means the end of the file was reached successfully, and we print a message indicating that.

On the other hand, if feof() returns zero, it suggests that an error occurred during the file reading process, and we print an appropriate error message.

Example of feof()

Let’s look at a complete example that shows the use of feof() in a C program:

#include <stdio.h>
int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    // Read characters from the file and count the number of characters
    int character;
    int count = 0;
    while ((character = getc(file)) != EOF) {
        count++;
    }

    if (feof(file)) {
        printf("Reached the end of the file.\n");
        printf("Total characters read: %d\n", count);
    } else {
        printf("An error occurred while reading the file.\n");
    }


    fclose(file);
    return 0;
}
You can also try this code with Online C Compiler
Run Code


Output

Error opening file.


In this example, we have a file named "example.txt" that we want to read from. In this code: 

1. We open the file in read mode using `fopen()` and check if the file was opened successfully by checking if the returned FILE pointer is NULL.
 

2. We initialize a variable `count` to keep track of the number of characters read from the file.
 

3. We start a while loop that reads characters from the file using `getc()` until EOF is encountered. Inside the loop, we increment the `count` variable for each character read.
 

4. After the loop, we use `feof()` to check if the end of the file was reached successfully.

 

5. If `feof()` returns a non-zero value, it means we reached the end of the file. We print a message indicating that and also print the total number of characters read.
 

6. If `feof()` returns zero, it suggests an error occurred while reading the file, and we print an appropriate error message.
 

7. Finally, we close the file using `fclose()` to release the associated resources.

When you run this program, it will read the contents of "example.txt", count the number of characters, and display the appropriate message based on whether the end of the file was reached successfully or an error occurred.

Frequently Asked Questions

What happens if I attempt to read from a file after reaching the end of file?

If you try to read from a file after reaching the end of file, getc() will keep returning EOF, and feof() will return a non-zero value, indicating that the end of file has been reached.

Can I use feof() to check for the end of file before reading from a file?

No, it's not recommended to use feof() before reading from a file. The end-of-file indicator is only set after a read operation attempts to read beyond the end of the file. It's better to use feof() after a read operation to check if the end of file was reached.

What's the difference between getc() and fgetc()?

getc() and fgetc() are equivalent functions in C. They both read a single character from a file and return it as an unsigned char cast to an int. The only difference is that getc() may be implemented as a macro, while fgetc() is always a function.

Conclusion

In this article, we discussed the concept of the end of a file in C and learned about two important functions: getc() and feof(). getc() reads a single character from a file, while feof() checks if the end of the file has been reached. We talked about their syntax, parameters, return values, and examples of their implementation.

You can also check out our other blogs on Code360.

Live masterclass