400 likes | 586 Views
Files and Streams. Chapter 9. Objectives. Use OCD to solve a problem involving files Study C++'s support for I/O with files Examine how interactive and file streams carry out I/O Look at string streams, how used for file I/O Learn about files in context of database-management systems
E N D
Files and Streams Chapter 9
Objectives • Use OCD to solve a problem involving files • Study C++'s support for I/O with files • Examine how interactive and file streams carry out I/O • Look at string streams, how used for file I/O • Learn about files in context of database-management systems • Show how I/O operations can be used for classes • Study ho class converters can use string streams C++ An Introduction to Computing, 3rd ed.
Problem: Processing Meteorological Data • Consider large amounts of weather related data. • Pressure readings recorded every 15 min • Data stored in file named pressure.dat • Must compute minimum, maximum, average • Program is to be created to • Read the data, • Calculate the statistics • Write the results to an output file C++ An Introduction to Computing, 3rd ed.
Objects C++ An Introduction to Computing, 3rd ed.
Operations • Prompt for, read string (file names) from keyboard • Initialize count, sum, maximum, minimum • Read a real value (reading) from file • Increment integer (count) by 1 • Add real value (reading) to real (sum) • Update minimum or maximum as necessary with reading • Repeat iii – vi until end of file • Write real values (minimum, maximum, sum/count) to output file C++ An Introduction to Computing, 3rd ed.
Additional Operations, Objects • Operations • Open the input, output files • Close the files as necessary • Objects C++ An Introduction to Computing, 3rd ed.
Algorithm • Prompt for, read name of input file into inputFileName • Open ifstream named inStream to file given by inputFileName • Initialize count to 0, sum to 0.0, maximum to smallest possible value, minimum to maximum possible value • Loop • Read real value for reading from inStream • If eof mark read, exit loop • Increment count • Add reading to sum • If reading < minimum, set minimum to reading • If reading > maximum, set maximum to reading End loop • Close inStream • Prompt for, read name of output file into outputFileName • Open an ofstream named outStream to file given by outputFileName • Write count to outStream • If count > 0, write minimum, maximum, sum/count to outStream • Close outStream C++ An Introduction to Computing, 3rd ed.
Coding and Testing • View source code in Figure 9.1 • Test runs Figure 9.2 • Note that screen output is only the prompting and the entry of the names • All input data came from the input files • All output reporting went to the output files C++ An Introduction to Computing, 3rd ed.
Declaring fstream Objects • An istream object named cin connects program and keyboard • An ostream object named cout connects the program and the screen These streams are constructed automatically. C++ An Introduction to Computing, 3rd ed.
Declaring fstream Objects • For doing I/O from/to a file a program must explicitly open a stream • Creates a connection between a program in memory and a text file C++ An Introduction to Computing, 3rd ed.
Basic fstream Operations • open() Establishes connection program to file • is_open() Returns true/false • >> Operator, inputs value from file • getline() Reads line of text into string object • << Operator, outputs value to file • eof() Returns true/false, end of file • close() Terminates connection between program, file C++ An Introduction to Computing, 3rd ed.
The open() Operation • Given:ifstream inStream;inStream.open( "pressure.dat"); • Parameter can also be a variable • If it is a string variable ( string fileName ) must use fileName.data() for correct parameter type • When input file is opened, read position pointer set to beginning of sequence of characters in the file C++ An Introduction to Computing, 3rd ed.
The open() Operation • When output file is opened, file is created on the disk, with write-position pointer pointing at the eof marker • Opening an ofstream to a file will create a new file • If file existed before, it is now (by default) destroyed • Otherwise, new file is created C++ An Introduction to Computing, 3rd ed.
The open() Operation • Possible to open the file with a mode argument as a second parameter C++ An Introduction to Computing, 3rd ed.
Initialization at Declaration • Possible to open at declaration of variableofstream outStream ("pressure.out");ifstream inStream ("pressure.in"); ExecutingProgram C++ An Introduction to Computing, 3rd ed.
Programming Defensively • The success or failure of a call to open a file should always be tested • Use inStream.open() • Us in an assert( ) mechanism • Call before proceeding with additional operations on the file • Consider application of some of these concepts in Figure 9.3 • Note the overloading of interactiveOpen() C++ An Introduction to Computing, 3rd ed.
The Input Operator • We have used cin >> x; • Value entered via the keyboard • C++ uses the same operator to bring values into variables from a streaminStream >> reading; • The reading pointer keeps track of where in the stream the program is currently reading C++ An Introduction to Computing, 3rd ed.
The getline() Function • Requires an istream object, a string objectgetline (nameStream, name); • Reads entire name into variable • Reads until it hits a newline character • Newline character read, not added to variable Note: the >> operator does not read the newline. The next >> skips it as white space. But if a getline is used next, it sees the newline and terminates. Think about what happens if you mix >> and getline calls. C++ An Introduction to Computing, 3rd ed.
The eof() Message • Can be used as a sentinel value to control an input loopfor ( ; ; ) { inStream >> reading; if (inStream.eof() ) break; // . . . process the input } • inStream.eof() returns true following execution of the input statement at this point C++ An Introduction to Computing, 3rd ed.
The Output Operator << • Overloaded to perform with ostream, ofstream objectsoutStream <<"\n--> There were a total of" << count << "values."; • Note that the write pointer is pushed forward, keeps pointing at the eof marker. C++ An Introduction to Computing, 3rd ed.
The close() Message • The file stream is disconnected when • The program leaves the scope of the fstream object (implicitly) • The close() message is executed (explicitly) • It is good practice to explicitly close a file when the program is done using it • If many files are accessed, the operating system may place a limit on how many files are open simultaneously C++ An Introduction to Computing, 3rd ed.
File Streams as Parameters • Parameters corresponding to file stream arguments must be reference parameters. • Because: • Reading from an ifstream alters the read position in that ifstream • Writing to the ofstream alters the write position in that ofstream C++ An Introduction to Computing, 3rd ed.
File I/O Example:Scanning for a Virus • A virus is a program that hides itself within other programs • It tries to proliferate by attaching itself to as many other programs as possible • It can be malicious or simply annoying • Deleting files • Displaying a goofy message on the screen C++ An Introduction to Computing, 3rd ed.
Combating Viruses • Virus detection and recovery • Identify a virus in a system • Remove the virus • Virus prevention • Keep new viruses from infecting a computer • Watch for behavior characteristic of viruses • Detection – see Figure 9.4 • Read lines from a file • Scan the line for specified string of text • If text found, display message C++ An Introduction to Computing, 3rd ed.
Manipulators for Random Access • Sequential access • Values in the file processed in sequence • Start at first values, read through to last • Random or direct access • Value accessed at any location in the file • Specify the location, then do the read • Two-Pass file process – Figure 9.5 • Read through values, calculate the average • Then go back through file to find deviations from the average C++ An Introduction to Computing, 3rd ed.
Status Operations To determine the status of a stream, the libraries provide these function members: • good() // returns true iff stream is ok • bad() // returns true iff stream is not ok • fail() // returns true iff last operation failed • eof() // returns true iff last file-read failed C++ An Introduction to Computing, 3rd ed.
Change-State Operations To change the state of a stream, the libraries provide these function members: • clear()// reset status to good • setstate(b)// set state bit b (one of ios_base::goodbit, ios_base::badbit, ios_base::failbit, or ios_base::eofbit ). C++ An Introduction to Computing, 3rd ed.
Read-Position Operations To manipulate the read-position within an ifstream, the libraries provide these: • tellg()// returns offset of current read-position from beginning of file • seekg(offset, base)// move read-position offset bytes from base (one of ios_base::beg, ios_base::cur, or ios_base::end) C++ An Introduction to Computing, 3rd ed.
Write-Position Operations To manipulate the write-position within an ofstream, the libraries provide these: • tellp()// returns offset of current write-position from beginning of file • seekp(offset, base)// move write-position offset bytes from base (one of ios_base::beg, ios_base::cur,or ios_base::end ) C++ An Introduction to Computing, 3rd ed.
Other Operations To look at the next character in an ifstream without advancing the read-position (i.e., without reading it), the libraries provide: • peek() // returns next char in the stream without reading it To “unread” the last char that was read, the libraries provide: • unget() // unread char most recently read C++ An Introduction to Computing, 3rd ed.
Another Operation To skip a given number of chars in the stream (or until a particular char is encountered), the libraries provide: • ignore(n, stopChar) // skip past n chars, or until stopChar is encountered C++ An Introduction to Computing, 3rd ed.
Manipulators without Arguments • Format control – use format manipulators • fixed used fixed point notation, reals • showpoint show decimal pt., trailing zeros • right right justify values, pad left • left left justify values, pad right • Example:cout << "\nTotal cost = $" << fixed << showpoint << cost << endl; • Note more extensive table of format manipulators on page 538 C++ An Introduction to Computing, 3rd ed.
Manipulators with Arguments • Format manipulators with arguments • setprecision(n) specify decimal digits • setw(n) specify width of field • These require#include <iomanip> • Examplecout << "\nTotal cost = $" << fixed << showpoint << setprecision(2) << cost << endl; C++ An Introduction to Computing, 3rd ed.
String Streams • C++ provides capability to • Read input from a string object • Write output to a string object • String streams provided • istringstream Input • ostringstream Output • stringstream For both input, ouput • View sample program, Figure 9.7 C++ An Introduction to Computing, 3rd ed.
Database • Businesses keep large amounts of data • For reviewing trends • For making business decisions • Data must be conveniently accessible • Managing the databases done byDatabase-Management Systems C++ An Introduction to Computing, 3rd ed.
Database Facilities • High-level views of the data • Access routines • Support for large databases • Security • Data sharing C++ An Introduction to Computing, 3rd ed.
Databases • Relational Databases organized into tables • Each column is a field of the table • Each row is a record in the table • The database-system takes care of • File names • Data representation • SQL – a language that provides query capabilities of tables • Further information • www.oracle.com • www.sybase.com C++ An Introduction to Computing, 3rd ed.
OBJECTive Thinking:Objects and Streams • Objects and File I/O • Possible to pass ifstream objects as parameters where we have used istream objects • ifstream fin ("nameFile.txt");aName.read(fin); • The ifstream class is derived from the istream class • An ifstream object is also an istream object • Similarly with ofstream and ostream objects • Note example in Figure 9.8 C++ An Introduction to Computing, 3rd ed.
Converter Methods • A converter is given an object of one time and produces an object as another type • Accessor converters • Constructor converters • Common to have converters that provide conversion to and from strings • Note example, Figure 9.9 • Driver to test converter operations, Figure 9.10 C++ An Introduction to Computing, 3rd ed.
Converter Methods • Sphere object converter, Figure 9.11 • Driver, Figure 9.12 Convertsfrom a Sphere to a string C++ An Introduction to Computing, 3rd ed.