when need to keep permanently File Input/Output when need to keep permanently
Streams C++ uses streams for input and output stream - is a sequence of data to be read (input stream) or a sequence of data generated by the program to be output (output stream) by default only standard streams are declared: cin (console input) cout (console output) files are used to store information permanently to do file input/output <fstream> needs to be included as well as using std::ifstream; and using std::ofstream; an input or output stream needs to be declared: ifstream fin; // input stream ofstream fout; // output stream before C++ program can read from or write to a file stream, the stream needs to be connected to a file. This is referred to as opening the file: fin.open(”myfile.dat”); // opening file string declaration and file opening in single statement ifstream fin(”myfile.dat”);
Streams (Cont.) a string variable can be used as file name c_str() function has to be applied to the string: string filename=”myfile.dat”; fin.open(filename.c_str()); after stream variable has been connected to a file, extraction and insertion operators can be used with a stream: fin >> var1 >> var2 >> var3; after the file is opened all the operations on the file is done through associated stream reading from a file while(fin >> myvar){ … } // any file while(getline(fin, myvar)){ … } // text file iterates until file ends or reading error closing stream: fin.close(); // closing file good style: closing all opened file streams before program ends
I/O Error Checking function fail() returns true if previous stream operation failed useful to check if file is opened successfully before performing operations on file useful function exit() - exists program immediately. to use exit, include <cstdlib> exit() accepts one integer as argument: convention: 0 - normal program termination; nonzero - abnormal example fin.open(”myfile.dat”); // opening file if (fin.fail()){ cout << ”Cannot open file myfile.dat”; exit(1); }
Streams as Parameters streams can be passed as parameters streams must be passed by reference void myfunc(ifstream &myinfile);
File I/O Review what is stream? what is the difference between input stream and output stream? what streams do not need definitions? how can you declare a stream? what do the following functions do? open() close() c_str() eof() fail() exit() how does one read from a file until its end? can a stream be passed as a parameter?