/***********************************************************************
* This demo program is designed to:
* Demonstrate two ways to read all the data from a file:
* while (!fin.eof())
* fin >> data;
* or...
* while (fin >> data)
* ;
************************************************************************/
#include <iostream>
#include <fstream>
using namespace std;
void usingEOF( const char fileName[]);
void notUsingEOF(const char fileName[]);
/**********************************************************************
* main(): A driver program for two functions: usingEOF and notUsingEOF
***********************************************************************/
int main()
{
// fileName reading
char fileName[256];
cout << "Filename? ";
cin >> fileName;
// choose between the two methods
cout << "Use the EOF method? (y/n) ";
char response;
cin >> response;
// execute
if (response == 'y' || response == 'Y')
usingEOF(fileName);
else
notUsingEOF(fileName);
return 0;
}
/****************************************************
* USING EOF
* This function will use the EOF method. Note that it will
* behave incorrectly when there is a white space immediately
* before the EOF character in the file
****************************************************/
void usingEOF( const char fileName[])
{
// open
ifstream fin(fileName);
if (fin.fail())
{
cout << "Unable to open file " << fileName << endl;
return;
}
// get the data and display it on the screen
char text[256];
// keep reading as long as:
// 1. not at the end of the file
while (!fin.eof())
{
// note that if this fails to rad anything (such as when there
// is nothing bug a white space between the file pointer and the
// end of the file), then text will keep the same value as the
// previous execution of the loop
fin >> text;
cout << "'" << text << "' ";
}
cout << endl;
// close
fin.close();
}
/****************************************************
* NOT USING EOF
* This function will loop until the read failed. This
* will correctly handle both the condition where there
* is valid data immediately before the EOF and when
* there is a white space before the EOF
****************************************************/
void notUsingEOF( const char fileName[])
{
// open
ifstream fin(fileName);
if (fin.fail())
{
cout << "Unable to open file " << fileName << endl;
return;
}
// get the data and display it on the screen
char text[256];
// keep reading as long as:
// 1. Not at the end of the file
// 2. Did not fial to read text into our variable
// 3. There is nothing else wrong with the file
while (fin >> text)
cout << "'" << text << "' ";
cout << endl;
// close
fin.close();
}
I love software development!