C feof() Function

beginner
13 min

C feof() Function

Welcome to the C feof() Function lesson! šŸŽÆ Today, we're diving into one of C's useful functions for dealing with input/output streams. Let's get started!

What is the feof() function?

The feof() function is a part of the C Standard Library and it is used to check if the end-of-file (EOF) has been reached on a stream. This can be very helpful when reading files, as we'll see later.

Understanding feof() function syntax

The feof() function takes one argument: the stream pointer. Here's the syntax:

c
int feof(FILE *stream);

The stream is the file stream to check whether it has reached EOF.

Real-world examples of feof() function

To better understand the feof() function, let's examine two practical examples:

Example 1: Reading a file with feof()

c
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); // Open example.txt for reading if (file == NULL) { printf("Unable to open file!\n"); return 1; } char character; while (!feof(file)) { // Keep reading until EOF is reached character = fgetc(file); // Read a character from the file printf("%c", character); // Print the character } fclose(file); // Close the file return 0; }

In this example, we open a file named example.txt and read its contents character by character until we reach EOF. The feof() function helps us stop the loop at the right time.

Example 2: Reading user input with feof()

c
#include <stdio.h> int main() { int number; while (1) { printf("Enter a number: "); scanf("%d", &number); if (feof(stdin)) { // Check if user has entered EOF (Ctrl+D on Linux/macOS, Ctrl+Z on Windows) printf("You have ended the input.\n"); break; } // Rest of the code printf("You entered: %d\n", number); } return 0; }

In this example, we read numbers from the user's input until they enter EOF. The feof(stdin) checks whether EOF has been entered, allowing us to exit the loop when the user is done inputting.

Important points about the feof() function

  • The feof() function only returns a non-zero value (1) when the end of the stream has been reached.
  • It's recommended to check feof() after reading the stream to ensure we don't prematurely assume EOF has been reached.

šŸ’” Pro Tip: The feof() function returns 0 when the stream is not at EOF, not when it is at EOF. Be sure to keep this in mind when using the function!

Quiz Time šŸ“

Quick Quiz
Question 1 of 1

What does the `feof()` function return when it is called on a file stream that has reached EOF?

Now that you understand the feof() function, let's practice using it in your C programming projects! šŸš€ Happy coding! šŸŽ‰