1 / 27

File Input and Output in C++

File Input and Output in C++. output data. input data. executing program. Keyboard. Screen. cin (of type istream). cout (of type ostream). Keyboard and Screen I/O. 0. #include <iostream>. 2. File I/O. 0. #include <fstream>. output data. input data. executing

Download Presentation

File Input and Output in C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. File Input and Output in C++

  2. output data input data executing program Keyboard Screen cin (of type istream) cout (of type ostream) Keyboard and Screen I/O 0 #include <iostream> 2

  3. File I/O 0 #include <fstream> output data input data executing program Report.txt Input.txt stream variable (of type ofstream) stream variable (of type ifstream) 3

  4. File I/O Statements #include <fstream> // Declare File Streams ifstream myInfile; // for input ofstream myOutfile;// for output myInfile.open(“myIn.dat”); // Open input file myOutfile.open(“myOut.dat”); // Open output file // Use file streams for input and output // Close files myInfile.close(); myOutfile.close(); 4

  5. File Stream Variables • File Streams are Variables • cin and cout are automatically created • You must declare your own stream variables to use file I/O • For Input… • Variable type is “ifstream” (input file stream) • For Output… • Variable type is “ofstream” (output file stream)

  6. Opening a File Opening a file • Associates your file stream variable with the external (disk) name for the file • If the input file does not exist on disk, open is not successful (fail state!) • If the output file does not exist on disk, a new file with that name is created • If the output file already exists, it is erased! • stream_name.open( “file_name” ); 6

  7. REMEMBER! • File input and output streams work exactly the same as cin and cout • You can use the same input commands • >>, get, getline, etc… • You can use the same output commands and modifiers • <<, endl, fixed, showpoint, setprecision, setw, etc… • Simply replace cin or cout with your custom declared stream variable

  8. Input Statements 0 SYNTAX These examples yield the same result. fileIn >> length; fileIn >> width; fileIn >> length >> width; ifstream fileIn; fileIn.open(“myFile.txt”); fileIn >> Variable >> Variable .. .; 8

  9. NOTE: shows the location of the buffer pointer i ch x i ch x 25 ‘A’ i ch x 25 ‘A’ i ch x 0 STATEMENTS CONTENTS POINTER POSITION int i; 25 A\n char ch; 16.9\n float x; fileIn >> i; 25A\n 16.9\n fileIn >> ch; 25 A\n 16.9\n fileIn >> x; 25 A\n 16.9\n Another example using >> 25 16.9 9

  10. Common Input mistake • You open the file stream infile for input • But then your input statements are for CIN • You didn't print a prompt since you shouldn't need one - you're reading from a FILE • The program appears to "hang" because it is waiting for KEYBOARD input! there's no prompt so you don't know it's waiting

  11. File Output • When a file is opened using an ofstream object, any output inserted into that stream is placed into the file buffer rather than on the screen • HINT: the contents of the output file will appear exactly as it would have appeared if it were placed on the monitor • first try the output using cout to verify it • once it is to your liking, change the stream name to your output file

  12. Output Statements SYNTAX These examples yield the same output fileOut << “The answer is “; fileOut << 3 * 4; fileOut << “The answer is “ << 3 * 4; ofstream fileOut; fileOut.open(“outfile.txt”); fileOut << Expression << Expression . . .;

  13. Run Time File Name Entry If you do not know up front what the name of the file to open will be, you can have the user enter the file name at the keyboard into a string. #include <string> // Contains conversion function c_str ifstream inFile; string fileName; cout << “Enter input file name: “ << endl; // Prompt cin >> fileName; // Convert string fileName to a C string type inFile.open(fileName.c_str()); 13

  14. Stream Fail State • When a stream enters the fail state, • Further I/O operations using that stream have no effect at all • The computer does not automatically halt the program or give any error message!! • Possible reasons for entering fail state include • Invalid input data (often the wrong type) • Opening an input file that doesn’t exist • Opening an output file on a disk that is already full or is write-protected 14

  15. Checking for a stream in fail state First way: Assuming myfile is declared as a filestream, either input or output, myfile.fail() returns true if the stream has failed, false otherwise • if (myfile.fail()) { cout << “filestream failed” << endl; return 1; // 1 to indicate something went wrong }

  16. Checking for a stream in fail state Second way: Assuming myfile is declared as a filestream, either input or output, myfile (the name of the stream) is also considered a bool variable. It has the value true if the stream is good, false if failed • if (!myfile) { cout << “filestream failed” << endl; return 1; // 1 to indicate something went wrong }

  17. Processing a file's data • you must know how the data is arranged in the file, or you can't read it • different ways to process all the data in the file • one is put a count in the beginning that tells you how many pieces there are • the other is to put in some indicator - a sentinel - at the end of the data

  18. Counter controlled reading infile >> howmany; ct = 0; while (ct < howmany) { infile >> data; // process data ct ++; } // don't forget to put the count in the file! And // make sure it's right!!

  19. Sentinel controlled reading • more flexible - can add or take away data in file without having to change count • either use literal sentinel number OR • use the file stream state itself as the event to end the loop

  20. Literal Sentinel value infile >> data; // priming read, remember? while (data != sentinel value) { // process data infile >> data; } // don't forget to put the sentinel value in // there!!

  21. File stream sentinel event infile >> data; while (infile) // the name is true while // the stream is ok { // process data infile >> data; } // does not require ANY special value at the // end of the file, handles ANY amount of data

  22. why not use eof()? • some people like to use while (! infile.eof()) which means to continue while the file stream hasn't set the eof flag to true yet • this flag is set ONLY when an attempt is made to read PAST the end of the file • other things can make the file stream fail that will NOT set the eof flag!

  23. Suppose... • suppose the input file didn't open, so the stream is in a fail state from the start • "while (infile)" is going to skip the loop altogether and go on, whereas... • "while (!infile.eof())" is going to fall into the loop and never get out, because the stream is failed, and the input statements in the loop are never executed! so eof () cannot ever become true!

  24. Suppose ... • suppose there is data of the wrong type in the file, like reading letters into an numeric variable • this makes the stream fail but does NOT set the eof() flag to true • so the loop "while (!infile.eof())" will be an infinite loop - again, input statements will be ignored because the data was bad, but eof() will never be true because we can't read and thus can't get past the end of file

  25. Fail States - why do you get one? • input files • can't open - input file doesn't exist • data of alphabetic type read into numeric variable • trying to read past end of file • output files • can't open because the PATH does not exist • can't write because there is no room on the device

  26. Errors in sentinel logic // This is an ERROR! while (infile) { infile >> data; // process data } it will process the last piece of data TWICE! Why?

  27. The correct way to do sentinel logic infile >> data; // priming read while (infile) // could be !infile.fail() { // process your data as needed infile >> data; // at BOTTOM of loop }

More Related