1 / 49

Introduction to C++ Part III Version 1.2

Introduction to C++ Part III Version 1.2. File I/O in C++. Stream Objects. cin – the standard input stream - an object of the istream class, cout – the standard output stream – an object of the ostream class. You have been introduced to these stream objects ….

liesel
Télécharger la présentation

Introduction to C++ Part III Version 1.2

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. Introduction to C++Part IIIVersion 1.2

  2. File I/O in C++

  3. Stream Objects • cin – the standard input stream - an object of the istream class, • cout – the standard output stream – an object of the ostream class You have been introduced to these stream objects … These streams are automatically created for you when your program executes. To use them you only need to #include <iostream> and the appropriate using directives.

  4. To do file I/O, we will use a new set of stream classes ifstream – objects of this class represent file input ofstream – objects of this class represent file output

  5. File I/O When a program takes input from a file, we say that it reads from the file. When a program puts data into a file, we say that it writes to the file. To read or write to a file, we create a stream object, and connect it to the file.

  6. Text Files Data in a file can either be text or binary. Everything in a text file appears as readable characters. You can look at the file with a text editor, such as notepad. Text files are sometimes referred to as Formatted files. This semester we will only deal with text files.

  7. The fstream classes We use objects of the ifstream class to read from a file, and objects of the ofstream class to write to a file. These classes are defined in <fstream>. To use them we must write #include <fstream>

  8. ifstream Operations >> stream extraction operator get ( ) extract one character getline( ) read a line of data into a string ignore( ) skip a character these ought to look familiar, they are the same functions we use on standard In and standard Out.

  9. Example Code ifstreamfileData (“c:\\thefile.txt”); char a; string s; int n; a = fileData.get( ); fileData.ignore( ); // pass over newline getline(fileData, s); fileData >> n;

  10. Declaring A Stream To use a stream object, it must first be declared ifstreaminStream; ofstreamoutStream;

  11. Stream variables A stream object is like any other variable, but there are some important exceptions: You cannot assign a value to a stream variable If you pass a stream variable as a parameter, you must pass it by reference.

  12. Connecting a Stream to a File ifstreaminputStream; inputStream.open (“theData.txt”); to program inputStream theData.txt Widget 123V89001 12.95 you can declare and connect to a file at the same time: ifstreaminputStream (“theData.txt”);

  13. Paths ifstreaminputStream; inputStream.open (“theData.txt”); if no path is specified, the file is assumed to be in the same directory as the program that is executing. When you code a \ in a pathname, you must write \\. Why? inputStream.open (“c:\\theData.txt”);

  14. More on Paths and Visual C++ Express You need the file in here when testing your code from the Console. If this is the folder for your project You need the file here when testing your code within C++ Visual Express Edition

  15. Reading From a Text File To read data from a text file, use the stream extraction operator, just as you would use it to read from the keyboard. string description; // no spaces string partNumber; // no spaces double price; ifstreaminputStream; inputStream.open (“theData.txt”); … inputStream >> description >> partNumber >> price; …

  16. Reading From a Text File If the data contains spaces, e.g. a person’s name then you must use getline. string name; ifstreaminputStream; inputStream.open (“theData.txt”); … getline(inputStream, name); …

  17. Type Safe I/O In the C programming language, input and output are done with very different libraries than those used in C++ (Although you can still use the C I/O libraries in C++ if you want to). One of the advantages to using the new C++ libraries is that C++ I/O is typesafe. The << and >> operators are overloaded to do the correct thing for all of the standard data types. These operators can also be overloaded for user defined data types.

  18. in the file, this is character data. inputStream theData.txt Widget 123V89001 12.95 12.95 convert from character to double …111000011010… double price; inputStream >> price; Data is read from the file and converted into the appropriate data type. price

  19. Writing to a Text File Use the stream insertion operator to write to a text file, just as if you were writing to the display. ofstreamoutputStream; outputStream.open (“theData.txt”); … outputStream << price;

  20. Opening an Output file If the named file does not exist, the file is created. If the named file already exists, it is opened, and the contents of the file are discarded, by default.

  21. Formatting the Output Most of the time, when we write data to a file, it is with the idea in mind that the data will be read in from this or some other program. It is up to the programmer to format the data in the output file, so that it can later be read in a meaningful way.

  22. Example int a = 5; int b = 15; int c = 239; ofstreammyOutputStream (“mydata.txt”); myOutputStream << a << b << c; 515239 What happens when you try to read this file?

  23. int a = 5; int b = 15; int c = 239; ofstreammyOutputStream (“mydata.txt”); myOutputStream << a << “ “ << b << “ “ << c; add white space to separate the fields!

  24. Closing the File It is good programming practice to close a file as soon as you are done using it. myOutputStream.close ( ); Although a file is closed automatically when a program ends normally, it is not closed if an error occurs and the program terminates abnormally. If the file is not closed, all of the data written to the file is lost!

  25. Mode Bits When a file is opened, you can supply bits that further define the file. These mode bits are defined in the ios class. The ios class contains a number of important constants we use in file I/O. ios::in open the file for reading, the default for ifstream ios::out open the file for writing, the default for ofstream ios::app open the file for appending. All data is written at the end of the file ios::ate open the file for appending. Data can be written anywhere ios::trunc open the file and discard contents, the default for ofstream ios::binary open the file for binary content, Note there is no ios::text which is the default

  26. Example #include <fstream> using std::ofstream; using std::ios; ofstreammyOutputStream (“TheData.txt”, ios::app); …

  27. Stream States Objects of all of the stream classes have a state that expresses the condition of the stream.. The stream classes provide functions to query the stream’s state. good( ) Everything’s fine eof( ) An input operation tried to read beyond the end of the file fail( ) An input operation failed to read the expected character, or an output operation failed to generate the desired characters bad( ) Indicates the loss of integrity of the underlying input or output sequence rdstate( ) Returns an int contain the status of all bits. fail, bad & eof

  28. Checking that a File Opened In C++, errors are not reported unless the programmer explicitly asks. For example, your program could call for a file to be opened and then read data from the file. If the file does not exist, no error is reported and you think that everything worked fine!

  29. ifstreammyInputStream; myInputStream.open (“someData.txt”); if (myInputStream.fail( )) { cout << “Could not open file”; } else { … check the state of the stream here… We could also write if (!myInputStream) {

  30. Because I/O is subject to so many errors, it is good programming practice to check the state of the stream after every I/O operation!

  31. Writing a loop that reads until end of file

  32. try to open the file print an error message and quit no did it open ? yes is the end of file flag set ? no

  33. continue with the rest of your program is the eof flag set ? yes no read a piece of data yes was the read good ? no was the eof flag set ? yes no process the data display an error message and quit

  34. inttheData; istreammyFile; myFile.open (“someData.txt”); while (!myFile.eof( )) { Start the read loop

  35. inttheData; istreammyFile; myFile.open (“someData.txt”); while (!myFile.eof( )) { myFile >> theData; Read some data

  36. inttheData; istreammyFile; myFile.open (“someData.txt”); while (!myFile.eof( )) { myFile >> theData; if ( myFile.good( ) ) { // process the data } Test the stream state -- only process the data if the read is good

  37. inttheData; istreammyFile; myFile.open (“someData.txt”); while (!myFile.eof( )) { myFile >> theData; if ( myFile.good( ) ) { // process the data } else if ( ! myFile.eof( ) ) { // print error message and quit } If the read fails, test for end of file

  38. inttheData; istreammyFile; myFile.open (“someData.txt”); while (!myFile.eof( )) { myFile >> theData; if ( myFile.good( ) ) { // process the data } else if ( ! myFile.eof( ) ) { // print error message and quit } } // end of the read loop

  39. We can read and test the state of the stream using the expression while (myFile >> theData)

  40. theFile.open("c:\\theFile02.txt"); while (theFile >> theData) { cout << "\nSuccessfully read in the value " << theData; } // dropped out, so read failed if (!theFile.eof( ) ) { cout << "\nCould not read an integer - bad data in the file."; } else { cout << "\nReached the end of the file."; }

  41. File Names as Input the filename must be stored in an array of characters. We will talk about char arrays in a later section… char fileName[80]; ifstreammyData; cout << “Enter in a file name: “; cin >> fileName; myData.open (fileName); … Alternatively you could write string fileName; cin >> fileName; myData.open(fileName.c_str( ) );

  42. Formatting Flags Formatting flags are defined in the ios class. Stream classes have a member function, setf( flag ) that sets these formatting flags. left left align output not set right right align output set dec output as decimal set hex output as hexadecimal not set oct output as octal (base 8) not set showpoint show decimal point on output not set scientific output in exponential format not set fixed output in fixed format (not scientific) not set

  43. You can combine flags with the | operator myStream.setf (ios::fixed | ios::showpoint); A flag remains set until it is unset. myStream.unsetf (ios::fixed);

  44. Stream Manipulators Stream manipulators go directly into the stream. They are inserted using the stream insertion operator dec hex oct endl setw (w) setprecision (n); setiosflags (flags); setfill (fillChar); myStream << setw (5) << theData;

  45. Side Effects You don’t want a function to have an unwanted side effect. One example would be setting I/O flags in a function and leaving them that way when you exit the function. The function flags returns a long data type that contains the settings of all of the I/O flags. long myFlags = myStream.flags ( ); … myStream.flags (myFlags); without an argument the function returns the flags. with an argument, the flags are restored to those set in the parameter.

  46. File Pointers Streams have pointers associated with them get pointer points to the place next character will be read from put pointer points to where the next character will be written tellg( ) returns current get pointer tellp ( ) returns current put pointer seekg ( ) positions get pointer seekp ( ) positions put pointer

  47. seekp (15); move 15 bytes from start of file seekp (-10, ios::end); move -10 bytes from end of file seekg (6, ios::cur); move 6 bytes from current position ios::beg position file pointer at beginning of the file ios::end position file pointer at end of the file ios::cur position file pointer at current file location

  48. Binary I/O Data is written to the output device exactly as it Is stored in memory. Binary I/O is done with the functions * read( ) * write( ) The parameters are the address of the data buffer and the number of bytes to read or write. The address must be cast to a char*

  49. Binary I/O Details CTesttestobj; ofstreamoutFile; outFile.open(“Test.bin”,ios::binary); outFile.write((char*)(&testobj),sizeof(testobj)); outFile.close( ); ifstreaminFile(“Test.bin”,ios::binary); inFile.read((char*)(&testobj),sizeof(testobj)); inFile.close( );

More Related