EOF, getc() and feof() in C

CProgrammingServer Side Programming

EOF

EOF stands for End of File. The function getc() returns EOF, on success..

Here is an example of EOF in C language,

Let’s say we have “new.txt” file with the following content.

This is demo!
This is demo!

Now, let us see the example.

Example

#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   fclose(f);
   getchar();
   return 0;
}

Output

This is demo!
This is demo!

In the above program, file is opened by using fopen(). When integer variable c is not equal to EOF, it will read the file.

FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}

getc()

It reads a single character from the input and return an integer value. If it fails, it returns EOF.

Here is the syntax of getc() in C language,

int getc(FILE *stream);

Here is an example of getc() in C language,

Let’s say we have “new.txt” file with the following content −

This is demo!
This is demo!

Now, let us see the example.

Example

#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   fclose(f);
   getchar();
   return 0;
}

Output

This is demo!
This is demo!

In the above program, file is opened by using fopen(). When integer variable c is not equal to EOF, it will read the file. The function getc() is reading the characters from the file.

FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}

feof()

The function feof() is used to check the end of file after EOF. It tests the end of file indicator. It returns non-zero value if successful otherwise, zero.

Here is the syntax of feof() in C language,

int feof(FILE *stream)

Here is an example of feof() in C language,

Let’s say we have “new.txt” file with the following content −

This is demo!
This is demo!

Now, let us see the example.

Example

#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   if (feof(f))
   printf("\n Reached to the end of file.");
   else
   printf("\n Failure.");
   fclose(f);
   getchar();
   return 0;
}

Output

This is demo!
This is demo!
Reached to the end of file.

In the above program, In the above program, file is opened by using fopen(). When integer variable c is not equal to EOF, it will read the file. The function feof() is checking again that pointer has reached to the end of file or not.

FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}
if (feof(f))
printf("\n Reached to the end of file.");
else
printf("\n Failure.");
raja
Published on 05-Nov-2018 15:22:35
Advertisements