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!
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.
feof() function syntaxThe feof() function takes one argument: the stream pointer. Here's the syntax:
int feof(FILE *stream);The stream is the file stream to check whether it has reached EOF.
feof() functionTo better understand the feof() function, let's examine two practical examples:
feof()#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.
feof()#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.
feof() functionfeof() function only returns a non-zero value (1) when the end of the stream has been reached.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!
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! š