Console C++ - fstream Template/Namespace Problems
fstream provides an operating system independent way
to read and write files.
Visual C++
inFile.fail() equals 1 if the file does not exist.
inFile.eof() becomes non-zero at the end of file.
I am showing several examples here. I have personally tested these with
Microsoft Visual C++ 6.0.
Note:
The problems here are due to mixing templates with regular header files.
- <iostream.h> is a regular header file which fails with "namespace std"
- <iostream> is a template which requires "namespace std"
The obvious solution is to use either all templates or all header files.
This example may seem a little strange, but
apstring (used in high school classes) uses iostream.h.
As a result, there can be problems.
This shows one way to deal with them.
It is also possible to use fstream.h is you omit std::.
#include // for ifstream - requires "namespace std"
#include // for cin & cout - fails with "namespace std"
int main(int argc, char* argv[])
{
char xx[81];
std::ifstream inFile; // note the str::
inFile.open("ReadMe.txt");
cout << "inFile.fail() = "<< inFile.fail() << endl; // fail() = 1 if file exists
cout << "inFile.eof() = " << inFile.eof() << endl; // eof() = 0 here
cin >> xx; // Just a pause
if (inFile.fail()==1) return 1; // exit if the file does not exist
cout << "aaaaaaaaaaaaaaaaaaaa"; // just to verify the the return exits the program
while (inFile.eof()==0) { // main loop to read the file
inFile >> xx; // Reads one word at a time
cout << xx << endl;
}
cout << "inFile.eof() = " <
This example uses a "string" variable for the filename, and
a try/catch structure to see if the file exists.
It also reads the text file one line at a time.
#include // for cin & cout - requires "namespace std"
#include // for ifstream - requires "namespace std"
#include
using namespace std;
int main(int argc, char* argv[])
{
char xx[81];
string filename_in;
filename_in = "readxme.txt"; // modify this to test for file not found
ifstream inFile;
try
{
inFile.open(filename_in.c_str()); // how to use a "string" variable
if(!inFile)
throw(filename_in);//If the file is not found, this calls the "catch"
}
catch(string filename_in)//This catches the infile and aborts process
{
cout << "Fatal error: File not found."<> xx; // Just a pause
while (inFile.eof()==0) { // main loop to read the file
inFile.getline(xx, 80); // Read one line
cout << xx << endl;
}
cout << "inFile.eof() = " <
This example uses a do..while loop and an alternate form of
the getline function.
#include // for cin & cout - requires "namespace std"
#include // for ifstream - requires "namespace std"
#include
using namespace std;
int main(int argc, char* argv[])
{
ifstream infile;
int x=0;
string word_array[100];
infile.open("Readme.txt");
do // main loop to read the file
{
getline(infile, word_array[x]); // Read one line
cout << word_array[x]; // Just for test
x++;
}while(infile.eof()==0);
infile.close();
return 0;
}
Author: Robert Clemenzi -
clemenzi@cpcug.org