C++ Detecting end of file:
The “eof” stands for “end-of-file”. It specifics the end of last record of the file.
The “eof” is a member function of object of ifstream (or fstream) class and it is used to detect the end-of-file. This function returns true value (or 1) if the end-of-file is reached otherwise it returns false value (or 0).
Normally the end-of-tile is detected by using the “eof” member function in a loop statement. For example, if “abc” is an object of the ifstream class, the “while statement” is written as:
while ( !abc.eof () )
The end-of-file can also be tested directly. The above object “abc” of ifstream can be tested for errors including end-of-file. If such a condition is true, the object returns a zero value otherwise a non-zero is returned. Thus the above statement is written as:
while (abc)
If end-of-file is encountered, then a zero value is returned and the loop is terminated.

Program:
Write a program to read records of students stored in data file “student.dat” by the above program and print the records on the screen.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <stdlib.h>
main ( )
{
char name [15], address [20], grade [5];
int s1, s2, s3, total, i=1;
ifstream getrec (“student.dat”);
clrscr ( );
if (! getrec)
{
cerr << “File opening error” << endl;
exit (1);
}
while (getrec)
{
cout << “Record #” << i++;
getrec >> name >> address >> s1 >> s2 >> s3 >> total >> grade >>;
cout << “\t” << name << “\t” << address << “\t” << s1 << “\t”
<< s2 << “\t” << s3 << “\t” << total << “\t” << grade << endl;
}
}
comment closed