1 / 39

Streams, Files, and Formatting

Streams, Files, and Formatting. Chapter 8. 8.1 Standard Input/Output Streams. Stream is a sequence of characters Working with cin and cout Streams convert internal representations to character streams >> input operator (extractor) << output operator (inserter)

crispin
Download Presentation

Streams, Files, and Formatting

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. Streams, Files, and Formatting Chapter 8

  2. 8.1 Standard Input/Output Streams • Stream is a sequence of characters • Working with cin and cout • Streams convert internal representations to character streams • >> input operator (extractor) • << output operator (inserter) • Streams have no fixed size

  3. Reading Data >> • Leading white space skipped • <nwln> also skipped • Until first character is located cin >> ch; • Also read character plus white space as a character • get and put functions

  4. CountChars.cpp // File: CountChars.cpp // Counts the number of characters and lines in // a file #include <iostream> #include <string> using namespace std; #define ENDFILE "CTRL-Z"

  5. CountChars.cpp int main() { const char NWLN = '\n'; // newline character char next; int charCount; int totalChars; int lineCount; lineCount = 0; totalChars = 0;

  6. CountChars.cpp cout << "Enter a line or press " << ENDFILE << ": "; while (cin.get(next)) { charCount = 0; while (next != NWLN && !cin.eof()) { cout.put(next); charCount++; totalChars++; cin.get(next); } // end inner while

  7. CountChars.cpp cout.put(NWLN); lineCount++; cout << "Number of characters in line " << lineCount << " is " << charCount << endl; cout << "Enter a line or press " << ENDFILE << ": "; } // end outer while cout << endl << endl << "Number of lines processed is " << lineCount << endl;

  8. CountChars.cpp cout << "Total number of characters is " << totalChars << endl; return 0; }

  9. 8.2 External Files • Batch • Requires use of data files (save to disk) • Batch can be run during off peak use • allows things to be complete at start of day • Interactive • Real time systems • Ok for smaller programs • Programs that complete quickly

  10. Files • Naming • .cpp .dat .out .in • How to attach files to the stream • stream object • external file name • internal name • open • Additional functions as part of fstream.h class

  11. Files • Declare the stream to be processed need to #include fstream ifstream ins; // input stream ofstream outs; // output stream • Need to open the files ins.open (inFile); outs.open (outFile);

  12. Files • #define associates the name of the stream with the actual file name • fail() function - returns true nonzero if file fails to open • Program CopyFile.cpp demonstrates the use of the other fstream functions • get , put, close and eof • discuss program

  13. CopyFile.cpp // File: CopyFile.cpp // Copies file InData.txt to file OutData.txt #include <cstdlib> #include <fstream> using namespace std; // Associate stream objects with external file // names #define inFile "InData.txt" #define outFile "OutData.txt"

  14. CopyFile.cpp // Functions used ... // Copies one line of text int copyLine(ifstream&, ofstream&); int main() { // Local data ... int lineCount; ifstream ins; ofstream outs;

  15. CopyFile.cpp // Open input and output file, exit on any // error. ins.open(inFile); if (ins.fail ()) { cerr << "*** ERROR: Cannot open " << inFile << " for input." << endl; return EXIT_FAILURE; // failure return } // end if

  16. CopyFile.cpp outs.open(outFile); if (outs.fail()) { cerr << "*** ERROR: Cannot open " << outFile << " for output." << endl; return EXIT_FAILURE; // failure return } // end if // Copy each character from inData to outData. lineCount = 0; do {

  17. CopyFile.cpp if (copyLine(ins, outs) != 0) lineCount++; } while (!ins.eof()); // Display a message on the screen. cout << "Input file copied to output file." << endl; cout << lineCount << " lines copied." << endl; ins.close(); outs.close(); return 0; // successful return }

  18. CopyFile.cpp // Copy one line of text from one file to another // Pre: ins is opened for input and outs for // output. // Post: Next line of ins is written to outs. // The last character processed from // ins is <nwln>; // the last character written to outs // is <nwln>. // Returns: The number of characters copied. int copyLine (ifstream& ins, ofstream& outs) {

  19. CopyFile.cpp // Local data ... const char NWLN = '\n'; char nextCh; int charCount = 0; // Copy all data characters from stream ins to // stream outs. ins.get(nextCh); while ((nextCh != NWLN) && !ins.eof()) { outs.put(nextCh); charCount++;

  20. CopyFile.cpp ins.get (nextCh); } // end while // If last character read was NWLN write it // to outs. if (!ins.eof()) { outs.put(NWLN); charCount++; } return charCount; } // end copyLine

  21. CopyFile.cpp Program Output Input file copied to output file. 37 lines copied.

  22. File Processing • Loop processing • for loops • while loops • Newline character • eof() function returns a False if file is not empty while ( ! ins.eof()) { do stuff }

  23. 8.3 Using External File Functions • Payroll Case Study • Two programs process the payroll • Design Process • Problem Analysis • Program Design • Program Implementation • Program Verification and Test

  24. Payroll Case Structure Chart processEmp

  25. ProcessEmp Structure Chart

  26. Payroll.cpp // File: Payroll.cpp // Creates a company employee payroll file // computes total company payroll amount #include <fstream> #include <cstdlib> #include "money.h" #include "money.cpp" using namespace std;

  27. Payroll.cpp // Associate streams with external file names #define inFile "EmpFile.txt" // employee file #define outFile "Salary.txt" // payroll file // Functions used ... // PROCESS ALL EMPLOYEES AND COMPUTE TOTAL money processEmp(istream&, ostream&); int main() { ifstream eds; ofstream pds; money totalPayroll;

  28. Payroll.cpp // Prepare files. eds.open(inFile); if (eds.fail ()) { cerr << "*** ERROR: Cannot open " << inFile << " for input." << endl; return EXIT_FAILURE; // failure return } pds.open(outFile); if (pds.fail()) {

  29. Payroll.cpp cerr << "***ERROR: Cannot open " << outFile << " for output." << endl; eds.close(); return EXIT_FAILURE; // failure return } // Process all employees and compute total // payroll. totalPayroll = processEmp(cin, cout); // Display result. cout << "Total payroll is " << totalPayroll << endl;

  30. Payroll.cpp // Close files. eds.close(); pds.close(); return 0; }

  31. Payroll.cpp // Insert processEmp here. // Process all employees and compute total // payroll amount // Pre: eds and pds are prepared for // input/output. // Post: Employee names and salaries are // written from eds to pds // and the sum of their salaries is returned. // Returns: Total company payroll money processEmp (istream& eds, ostream& pds) {

  32. Payroll.cpp string firstName; string lastName; float hours; // input: hoursWorked money rate; // input: hourly rate money salary; // output: gross salary money payroll; // return value - total company payroll payroll = 0.0; // Read first employee's data record. eds >> firstName >> lastName >> hours >> rate;

  33. Payroll.cpp while (!eds.eof()) { salary = hours * rate; pds << firstName << lastName << salary << endl; payroll += salary; // Read next employee's data record. eds >> firstName >> lastName >> hours >> rate; } // end while return payroll; } // end processEmp

  34. PayrollFile.cpp Program Output Total payroll is $677.38

  35. 8.4 More on Reading String Data • Getline - could be used to process an entire line of data • Use # as a delimiter character getline (eds, name, ‘#’); • Advance the newline getline (eds, name, ‘\n’); • Use care when choosing cin, get or getline

  36. 8.5 Input/Output Manipulators • Chapter 5 covered setf, unsetf, precision and width • Can be used with the cout and << • Table 8.3 lists various manipulator functions (setiosflags, setprecision, setw) • #include iomanip when using • Can be used with external files like stdout and stdin

  37. Formatting with State Flags • Depending on the setiosflags or unsetiosflags • Output can be controlled by other format state flag • Flags are enumerated types • ios::flagname • Table 8.3 lists some flags • boolalpha, fixed, left, right, showpoint etc

  38. 8.6 Common Programming Errors • Connecting streams and external files • Declare stream object and open the file • Watch use of while loops when processing • Test values see what you actually have • Reading past the eof • White space • Newline character • Formatting via flags

  39. C++ has support both for input and output with files through the following classes: • ofstream: File class for writing operations (derived from ostream) • ifstream: File class for reading operations (derived from istream) • fstream: File class for both reading and writing operations (derived from iostream) • Open a file • The first operation generally done on an object of one of these classes is to associate it to a real file, that is to say, to open a file. The open file is represented within the program by a stream object (an instantiation of one of these classes) and any input or output performed on this stream object will be applied to the physical file. • In order to open a file with a stream object we use its member function open(): • void open (const char * filename, openmode mode);where filename is a string of characters representing the name of the file to be opened and mode is a combination of the following flags: These flags can be combined using bitwise operator OR: |. For example, if we want to open the file "example.bin" in binary mode to add data we could do it by the following call to function-member open: ofstream file;file.open ("example.bin", ios::out | ios::app | ios::binary); All of the member functions open of classes ofstream, ifstream and fstream include a default mode when opening files that varies from one to the other: The default value is only applied if the function is called without specifying a mode parameter. If the function is called with any value in that parameter the default mode is stepped on, not combined. Since the first task that is performed on an object of classes ofstream, ifstream and fstream is frequently to open a file, these three classes include a constructor that directly calls the open member function and has the same parameters as this. This way, we could also have declared the previous object and conducted the same opening operation just by writing: ofstream file ("example.bin", ios::out | ios::app | ios::binary); Both forms to open a file are valid. You can check if a file has been correctly opened by calling the member function is_open(): bool is_open();that returns a bool type value indicating true in case that indeed the object has been correctly associated with an open file or false otherwise. Closing a file When reading, writing or consulting operations on a file are complete we must close it so that it becomes available again. In order to do that we shall call the member function close(), that is in charge of flushing the buffers and closing the file. Its form is quite simple: void close ();Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes. In case that an object is destructed while still associated with an open file, the destructor automatically calls the member function close. Text mode files Classes ofstream, ifstream and fstream are derived from ostream, istream and iostream respectively. That's why fstream objects can use the members of these parent classes to access data. Generally, when using text files we shall use the same members of these classes that we used in communication with the console (cin and cout). As in the following example, where we use the overloaded insertion operator <<: Data input from file can also be performed in the same way that we did with cin: • This last example reads a text file and prints out its content on the screen. Notice how we have used a new member function, called eof that ifstream inherits from class ios and that returns true in case that the end of the file has been reached. • Verification of state flags • In addition to eof(), other member functions exist to verify the state of the stream (all of them return a bool value): • bad() • Returns true if a failure occurs in a reading or writing operation. For example in case we try to write to a file that is not open for writing or if the device where we try to write has no space left. • fail() • Returns true in the same cases as bad() plus in case that a format error happens, as trying to read an integer number and an alphabetical character is received. • eof() • Returns true if a file opened for reading has reached the end. • good() • It is the most generic: returns false in the same cases in which calling any of the previous functions would return true. • In order to reset the state flags checked by the previous member functions you can use member function clear(), with no parameters. • get and put stream pointers • All i/o streams objects have, at least, one stream pointer: • ifstream, like istream, has a pointer known as get pointer that points to the next element to be read. • ofstream, like ostream, has a pointer put pointer that points to the location where the next element has to be written. • Finally fstream, like iostream, inherits both: get and put • These stream pointers that point to the reading or writing locations within a stream can be read and/or manipulated using the following member functions: • tellg() and tellp() • These two member functions admit no parameters and return a value of type pos_type (according ANSI-C++ standard) that is an integer data type representing the current position of get stream pointer (in case of tellg) or put stream pointer (in case of tellp). • seekg() and seekp() • This pair of functions serve respectively to change the position of stream pointers get and put. Both functions are overloaded with two different prototypes: • seekg ( pos_type position );seekp ( pos_type position ); • Using this prototype the stream pointer is changed to an absolute position from the beginning of the file. The type required is the same as that returned by functions tellg and tellp. • seekg ( off_type offset, seekdir direction );seekp ( off_type offset, seekdir direction ); • Using this prototype, an offset from a concrete point determined by parameter direction can be specified. It can be: The values of both stream pointers get and put are counted in different ways for text files than for binary files, since in text mode files some modifications to the appearance of some special characters can occur. For that reason it is advisable to use only the first prototype of seekg and seekp with files opened in text mode and always use non-modified values returned by tellg or tellp. With binary files, you can freely use all the implementations for these functions. They should not have any unexpected behavior. The following example uses the member functions just seen to obtain the size of a binary file: Binary files In binary files inputting and outputting data with operators like << and >> and functions like getline, does not make too much sense, although they are perfectly valid. File streams include two member functions specially designed for input and output of data sequentially: write and read. The first one (write) is a member function of ostream, also inherited by ofstream. And read is member function of istream and it is inherited by ifstream. Objects of class fstream have both. Their prototypes are: write ( char * buffer, streamsize size ); read ( char * buffer, streamsize size );Where buffer is the address of a memory block where the read data are stored or from where the data to be written are taken. The size parameter is an integer value that specifies the number of characters to be read/written from/to the buffer. • Buffers and Synchronization • When we operate with file streams, these are associated to a buffer of type streambuf. This buffer is a memory block that acts as an intermediary between the stream and the physical file. For example, with an out stream, each time the member function put (write a single character) is called, the character is not written directly to the physical file with which the stream is associated. Instead of that, the character is inserted in the buffer for that stream. • When the buffer is flushed, all data that it contains is written to the physic media (if it is an out stream) or simply erased (if it is an in stream). This process is called synchronization and it takes place under any of the following circumstances: • When the file is closed: before closing a file all buffers that have not yet been completely written or read are synchronized. • When the buffer is full:Buffers have a certain size. When the buffer is full it is automatically synchronized. • Explicitly with manipulators: When certain manipulators are used on streams a synchronization takes place. These manipulators are: flush and endl. • Explicitly with function sync(): Calling member function sync() (no parameters) causes an immediate syncronization. This function returns an int value equal to -1 if the stream has no associated buffer or in case of failure.

More Related