Programming in C: Unit V: File processing

Detecting the End-of-File

Syntax with Example C Programs

When reading or writing data from files, we often do not know exactly how long the file is. For example, while reading the file, we usually start reading from the beginning and proceed towards the end of the file.

DETECTING THE END-OF-FILE

When reading or writing data from files, we often do not know exactly how long the file is. For example, while reading the file, we usually start reading from the beginning and proceed towards the end of the file. In C, there are two ways to detect EOF:

• While reading the file in text mode, character by air character, the programmer can compare the character that has been read with the EOF, which is a symbolic constant defined in stdio.h with a value -1. The following statement, does that

while (1)

{

c = fgetc (fp);

// here c is an int variable

if (c==EOF)

break;

printf("%c", c);

}

• The other way is to use the standard library function feof() which is defined in stdio.h. The feof() is used to distinguish between two cases:

When a stream operation has reached the end of a file

When the EOF (end of file) error code has returned an error indicator even when the end of the file has not been reached

The prototype of feof() can be given as  

int feof (FILE *fp);

The function takes a pointer to the FILE structure of the stream to check as an argument and returns zero (false) when the end of file has not been reached and a one (true) if the EOF has been reached. Look at the following:

(The output assumes that a file Student.DAT already exists and conatins the following data: 1 Aditya 2 Chaitanya 3 Goransh)

#include <stdio.h>

main ()

{

FILE *fp;

char str[80];

fp = fopen("Student.DAT", "r");

if (fp==NULL)

{

printf("\n The file could not be opened");

exit (1);

}

/* The loop continues until fp reaches the end-of-file */

while (!feof (fp)

{

fgets (str, 79, fp);

// Reads 79 bytes at a time

printf("\n %s", str);

}

printf("\n\n File Read. Now closing the file");

fclose (fp);

return 0;

}

Output

1 Aditya 2 Chaitanya 3 Goransh

Programming in C: Unit V: File processing : Tag: : Syntax with Example C Programs - Detecting the End-of-File