View
33
Download
0
Category
Preview:
DESCRIPTION
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 - PowerPoint PPT Presentation
Citation preview
Files and Streams
Chapter 9
C++ An Introduction to Computing, 3rd ed. 2
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. 3
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. 4
Objects
DescriptionSoftware Objects
Type Kind Namename of input file string varying inputFileName
pressure reading double varying reading
number of readings int varying count
minimum reading double varying minimum
maximum reading double varying maximum
sum of readings double varying sum
average reading double varying average
name of output file string varying outputFileName
C++ An Introduction to Computing, 3rd ed. 5
Operationsi. Prompt for, read string (file names) from
keyboardii. Initialize count, sum, maximum, minimumiii. Read a real value (reading) from fileiv. Increment integer (count) by 1v. Add real value (reading) to real (sum)vi. Update minimum or maximum as necessary
with readingvii. Repeat iii – vi until end of fileviii. Write real values (minimum, maximum,
sum/count) to output file
C++ An Introduction to Computing, 3rd ed. 6
Additional Operations, Objects
Operations• Open the input, output files• Close the files as necessary
Objects
DescriptionSoftware Objects
Type Kind Nameinput stream ifstream varying inStream
output stream ofstream varying outStream
C++ An Introduction to Computing, 3rd ed. 7
Algorithm1. Prompt for, read name of input file into inputFileName2. Open ifstream named inStream to file given by inputFileName3. Initialize count to 0, sum to 0.0, maximum to smallest possible value,
minimum to maximum possible value4. Loop
a. Read real value for reading from inStreamb. If eof mark read, exit loopc. Increment countd. Add reading to sume. If reading < minimum, set minimum to readingf. If reading > maximum, set maximum to reading
End loop5. Close inStream6. Prompt for, read name of output file into outputFileName7. Open an ofstream named outStream to file given by outputFileName8. Write count to outStream9. If count > 0, write minimum, maximum, sum/count to outStream10. Close outStream
C++ An Introduction to Computing, 3rd ed. 8
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. 9
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.
These streams are constructed automatically.
C++ An Introduction to Computing, 3rd ed. 10
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. 11
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 betweenprogram, file
C++ An Introduction to Computing, 3rd ed. 12
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. 13
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. 14
The open() Operation
Possible to open the file with a mode argument as a second parameter
Mode Description
ios::inopen for input, non destructive, read pointer at beginning
ios::trunc Open file, delete contents it contains
ios::out Open for output, use ios::trunc
ios::appOpen for output, nondestructive, write position at end of file
ios::ateOpen existing file with read (or write) position at end of file
ios::binary Open file in binary mode
C++ An Introduction to Computing, 3rd ed. 15
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. 16
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. 17
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 stream inStream >> reading;
The reading pointer keeps track of where in the stream the program is currently reading
C++ An Introduction to Computing, 3rd ed. 18
The getline() Function
Requires an istream object, a string object getline (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.
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. 19
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
The eof() Message
C++ An Introduction to Computing, 3rd ed. 20
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. 21
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. 22
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. 23
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. 24
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. 25
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. 26
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. 27
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 ofios_base::goodbit,ios_base::badbit,ios_base::failbit, orios_base::eofbit ).
C++ An Introduction to Computing, 3rd ed. 28
Read-Position Operations
To manipulate the read-position within an ifstream, the libraries provide these:tellg() // returns offset of current
read-position frombeginning of file
seekg(offset, base) // move read-position
offset bytes from base (one of ios_base::beg,ios_base::cur, orios_base::end)
C++ An Introduction to Computing, 3rd ed. 29
Write-Position Operations
To manipulate the write-position within an ofstream, the libraries provide these:
tellp() // returns offset of currentwrite-position frombeginning of file
seekp(offset, base) // move write-position offset bytes from base (one of ios_base::beg,ios_base::cur, orios_base::end )
C++ An Introduction to Computing, 3rd ed. 30
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 itTo “unread” the last char that was read, the
libraries provide:unget() // unread char most recently
read
C++ An Introduction to Computing, 3rd ed. 31
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. 32
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. 33
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. 34
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. 35
Database
Businesses keep large amounts of data• For reviewing trends• For making business decisions
Data must be conveniently accessible• Managing the databases done by
Database-Management Systems
C++ An Introduction to Computing, 3rd ed. 36
Database Facilities
High-level views of the data
Access routines
Support for large databases
Security
Data sharing
C++ An Introduction to Computing, 3rd ed. 37
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 tablesFurther information• www.oracle.com• www.sybase.com
C++ An Introduction to Computing, 3rd ed. 38
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. 39
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. 40
Converter Methods
Sphere object converter, Figure 9.11• Driver, Figure 9.12
Convertsfrom a Sphere
to a string
Convertsfrom a Sphere
to a string
Recommended