FILE I/O
C++
#include
So far, we have been using
the iostream standard library, which
provides cin and cout methods for reading
from standard input (key board) and writing to
standard output (screen) respectively.
#include
Read from and write to a file requires the
fstream library.
We will concern ourselves with text files only
in CIS 22A & B.
Three new types: ifstream, ofstream, fstream.
We will use only the first two. There are many
ways to do this – I have tried to pick an easy
path that parallels all languages.
File Output
# include
//Declare file pointer
ofstream fileOut;
//Open file
fileOut.open(". . . “);
//Redirect output to this object
fileOut << " Happy? “;
//Close file
fileOut.close();
File Input – opening the file
#include
//Declare pointer to file
ifstream fileIn;
fileIn.open(". . . “);
cout << fileIn.fail(); //interesting but not necessary
fileIn >> variable_of_your_choice;
getline( , ); //picks up the newline
File Input – part of GIGO Rule
if (fileIn.fail()) //Always check that it exists
{
cout << "No such file";
system("pause");
exit(100);
}
File Input – Simple redirection
fileIn >> variable_of_your_choice;
getline( , ); //picks up the newline
fileIn.get(ch); //where ch is type char
File Input – looping until end of file
int count = 0;
while(!inFile.eof())
{
inFile>> mlsNum;
fileIn >> price >> sqFt;
. . .
count++;
}
Passing a file to a function
//Input file
void getData(ifstream& myFile, . . .
//Output file
Void output(ofstream& fileOut, . . .