Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

How to use foef() in C

Ayesha Naeem

The feof() function in C detects the end of a file.

To use the feof() function, the program needs to include the stdio.h header file as shown below:

#include <stdio.h>

Parameters and Return Value

The feof() function only accepts a pointer to a FILE object as the parameter.

feof() returns a single non-zero value of type int if the end of a file is reached, otherwise it returns a 0.

Examples

The following code demonstrates how to open, read, and detect the end of a file:

main.c
educative.txt
#include <stdio.h>

int main()
{
  // open a file
  FILE *ptr = fopen("educative.txt","r");
  // check for error
  if(ptr == NULL)
  {
      printf("Error opening file");
  }
  // check for end of file
  while(!(feof(ptr)))
  {
      //get the character and print
      printf("%c", fgetc(ptr));
  }
  // close the file
  fclose(ptr);

}

Explanation

  • The above code employs the fopen() function to open the educative.txt file. The program stores the file pointer in ptr and checks for a NULL value to detect any errors.
  • The fgetc() function displays one character of the file at a time in a while loop. fgetc() returns the character indicated by the file pointer and advances the file pointer onto the next character.
  • The while loop terminates once the feof() function detects the end of the file

RELATED TAGS

c

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring