© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors
© Janice Regan, CMPT Streams Streams Special objects Deliver program input and output to/from your program Think of a stream of output, cout Think of a stream of input, cin Think of << as an operator to move data from your program to an ouput stream Think of >> as an operator to move data from an input stream into your program
© Janice Regan, CMPT Streams A stream can be thought of as a flow of characters An input stream flows into your program Can come from keyboard (cin) Can come from file An output stream flows out of your program Can go to screen (cout, or cerr) Can go to file
© Janice Regan, CMPT Reading/Writing data (1) Use iostream objects cin and cout cin >> num; Waits on-screen for keyboard entry Value entered at keyboard is placed in the memory location reserved for variable num, that is the entered value is "assigned" to num
© Janice Regan, CMPT Reading/Writing data (2) cout << num; Value from the memory location reserved for variable num, is displayed on the screen To remember direction of >> think of it as an arrow pointing to where the data is going cin >> num; //value is being put into variable num cout << num; //value in num is being sent to the screen
© Janice Regan, CMPT Error Output Output with cerr cerr works in the same way as cout Two different streams of information cout and cerr Both streams are displayed on the console (screen) Can separate the two streams Display error information to the screen Redirect output to a file Provides mechanism for distinguishing between regular output and error output.
© Janice Regan, CMPT Other Streams The programmer can define other streams Stream can flow into a file Can have multiple streams each flowing into their own file Streams can flow out of files Can have multiple streams each flowing out of its own file Programmer defined streams can be used like C++ defined streams cin, cout, and cerr Each stream actually has more flexibility and functionality than we have discussed so far
© Janice Regan, CMPT File I/O Libraries To access the objects and functions needed to use your own streams You need the library fstream #include using namespace std;
© Janice Regan, CMPT Create a stream First create a stream to read from Declare a variable of type ifstream ifstream myInputStream; OR a stream to write to Declare a variable of type ofstream ofstream myOutputStream; Types ifstream and ofstream are defined in library fstream
© Janice Regan, CMPT Connect your file to the stream Once you have declared a variable to refer to the input or output stream then you need to connect your input or output file to that stream. This process of connecting to the file is called “opening the file” myInputStream.open("infile.txt“); myOutputStream.open(“outfile.txt”);
© Janice Regan, CMPT File Names The filenames "infile.txt“, “outfile.txt” used in the open statement refer to files that exist (for read or write) or will be created (for write) on your computers disk. If input or output files are kept in the same folder as the executable then infile.txt and outfile.txt will be the actual names of the files Otherwise infile.txt and outfile.txt must be paths to the files for example D:\CourseData\cmpt128\try123\infile.txt
© Janice Regan, CMPT Using files for input / output Within C++ programs information is read from files or written to files The file name (path) of the file saved on the computer’s disk for example infile.txt or outfile.txt is used only to connect to the stream you create in your program All access to the file once it has been opened is done using the stream name for example myInputStream or myOutputStream
© Janice Regan, CMPT Reading data from a file cin is an input stream You have now declared and connected to your own input stream myInputStream To read data from your input stream use myInputStream just like you used cin to read from the keyboard stream myInputStream >> variablename;
© Janice Regan, CMPT Writing data to a file cout is an output stream You have now declared and connected to your own output stream To write data to this stream use myOutputStream just like you used cout myOutputStream << variablename;
© Janice Regan, CMPT Breaking the connection When the program has completed reading from or writing to the file, the connection to the file is no longer needed. The programmer needs to break the connection between the program and the file myInputStream.close(); myOutputStream.close();
© Janice Regan, CMPT Checking if the file opened Sometimes we are unable to open a file File does not exist, cannot be found We cannot create the new file Disk is full Can not write where we asked to create the file Need to check that the file was actually opened if ( myOutputStream.fail( ) )
© Janice Regan, CMPT Check: using function fail( ) Need to check that the file was actually opened myOutputStream.open(“infile.txt"); if ( myOutputStream.fail( ) ) { cout << "File open failed.\n"; exit(1); }
© Janice Regan, CMPT File Example: Simple File Input/Output (1) #include using namespace std; int main () { ifstream inStream; ofstream outStream; //declare variables and constants double meanValue = 0.0; double input1=0.0, input2 = 0.0; double input3 = 0.0, input4=0.0; inStream.open("inputFile"); if ( inStream.fail( ) ) { cerr << "inputFile not opened" << endl; return 1; } outStream.open("outputFile"); if ( outStream.fail( ) ) { cerr << "outputFile not opened" << endl; return 2; }
© Janice Regan, CMPT File Example: Simple File Input/Output (2) myInStream >> input1 >> input2 >> input3 >> input4; meanValue = (input1+input2+input3+input4)/4.0; myOutStream << "The mean of the first four input values is "; myOutStream << meanValue << endl; myInStream.close( ); myOutStream.close( ); Input FileOutput File The mean of the first four input values is 3.50
© Janice Regan, CMPT Formatting Output We have seen how to format output on stream cout using manipulators We can use the same manipulators to format on any output stream
© Janice Regan, CMPT Opening output files When you open an output file using the C++ syntax we have discussed You are able write information to the file The information you write after you open the file will begin at the beginning of the file If the output file does not exist it will be created If the output file already exists when you open it, then the information you write will overwrite any information already in the file What if you want to add information to the end of an existing file instead? The process of adding information to the end of the file is called appending information to the file
© Janice Regan, CMPT Appending to a File ofstream outStream; outStream.open("important.txt", ios::app); If file doesn’t exist it will be created If file already exists information will be added to the end of the existing file
© Janice Regan, CMPT Rereading from a file If you want to reread the data in a file you can Close the file, Clear any status saved from the last use of the file. Reopen the file. inStream.open("stuff.txt"); ⋮ inStream.close(); inStream.clear(); inStream.open("stuff.txt"); ⋮ inStream.close();
© Janice Regan, CMPT Checking End of File In many situations we have an input file containing data with the following properties Data for many sets of observations (e.g. name and age and student number for a series of students) Data contains an unknown number of sets of observations In these situations we often want to read and process each set of observations sequentially: Read and process each set of observations Begin with the first set in the file Continue until the last set is processed Done when the end of the file is reached To implement solutions of this type we need to be able to test to see if we are at the end of the file
© Janice Regan, CMPT Endfile controlled Loop // Data is read from a file, one line (three values at a time // Each time a line is read the cost is updated // After all data is read the cost is printed to the screen ifstream infile; double v1,v2, v3, cost; infile.open(“filename”); // should check if file has been opened infile >> v1 >> v2 >> v3; while ( !infile.eof( ) ) // while not at the end of file { cost += (v1 + v2 / v3); infile >> v1 >> v2 >> v3; } infile.close( ); cout << “Total cost is “ << cost << endl;
© Janice Regan, CMPT Endfile controlled Loop T infile.eof( ) infile >> v1; Initial statement Loop condition F Statement 1; … Statement m; Update statement
© Janice Regan, CMPT // Data is read from a file, with one value on each line // Each time a line is read the cost is updated // After all data is read the cost is printed to the screen #include …. ifstream infile; infile.open("filename"); // should check if file has been opened while ( !infile.eof() ) { if( !( infile >> v1) && !infile.eof() ) { exit(1)} // exit if variable is not read cost += v1; } infile.close( ); cout << "Total cost is " << cost << endl; Check if variable was read
© Janice Regan, CMPT Buffered output (1) When writing output to a file Output is temporarily stored in an internal buffer Output from multiple write statements may be stored in the same buffer Output is only written to the screen when the buffer is full. Output is written one buffer at a time. Closing the file causes the last partially full buffer to be written to the screen What happens to the output buffer when the program stops due to an error?
© Janice Regan, CMPT Buffered output (2) When a program stops for an error, the final partially full buffer may not be printed When a program requires that output be displayed immediately (not buffered) outStream.flush(); Member function flush, for all output streams All buffered output is written immediately
© Janice Regan, CMPT Return Value controlled Loop T infile >> v1 Loop condition F Statement 1; … Statement m;
Catching a character int main() { int numOne; cout "; while ( !(cin >> numOne) ) { cin.clear(); //clears the error flag cin.sync(); //removes remaining characters from the input stream //NEVER NEVER use cin.sync() if there is no data in the input stream cout << "You typed a character not an integer, Try again" << endl; } cout << "The integer you entered was: " << numOne <<endl; return 0; } © Janice Regan, CMPT