Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Files and Streams Chapter 9

2 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

3 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

4 C++ An Introduction to Computing, 3rd ed. 4 Objects Description Software Objects TypeKindName name 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

5 C++ An Introduction to Computing, 3rd ed. 5 Operations i. Prompt for, read string (file names) from keyboard ii. Initialize count, sum, maximum, minimum iii. Read a real value ( reading ) from file iv. Increment integer ( count ) by 1 v. Add real value ( reading ) to real ( sum ) vi. Update minimum or maximum as necessary with reading vii. Repeat iii – vi until end of file viii. Write real values ( minimum, maximum, sum/count ) to output file

6 C++ An Introduction to Computing, 3rd ed. 6 Additional Operations, Objects Operations Open the input, output files Close the files as necessary Objects Description Software Objects TypeKindName input stream ifstream varying inStream output stream ofstream varying outStream

7 C++ An Introduction to Computing, 3rd ed. 7 Algorithm 1. Prompt for, read name of input file into inputFileName 2. Open ifstream named inStream to file given by inputFileName 3. Initialize count to 0, sum to 0.0, maximum to smallest possible value, minimum to maximum possible value 4. Loop a. Read real value for reading from inStream b. If eof mark read, exit loop c. Increment count d. Add reading to sum e. If reading < minimum, set minimum to reading f. If reading > maximum, set maximum to reading End loop 5. Close inStream 6. Prompt for, read name of output file into outputFileName 7. Open an ofstream named outStream to file given by outputFileName 8. Write count to out S tream 9. If count > 0, write minimum, maximum, s um/count to outStream 10. Close outStream

8 C++ An Introduction to Computing, 3rd ed. 8 Coding and Testing View source code in Figure 9.1Figure 9.1 Test runs Figure 9.2Figure 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

9 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.

10 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

11 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 between program, file

12 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

13 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

14 C++ An Introduction to Computing, 3rd ed. 14 The open() Operation Possible to open the file with a mode argument as a second parameter ModeDescription ios::in open 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::app Open for output, nondestructive, write position at end of file ios::ate Open existing file with read (or write) position at end of file ios::binary Open file in binary mode

15 C++ An Introduction to Computing, 3rd ed. 15 Initialization at Declaration Possible to open at declaration of variable ofstream outStream ("pressure.out"); ifstream inStream ("pressure.in"); Executing Program

16 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.3Figure 9.3 Note the overloading of interactiveOpen()

17 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

18 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.

19 C++ An Introduction to Computing, 3rd ed. 19 Can be used as a sentinel value to control an input loop for ( ; ; ) { 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

20 C++ An Introduction to Computing, 3rd ed. 20 The Output Operator << Overloaded to perform with ostream, ofstream objects outStream There were a total of" << count << "values."; Note that the write pointer is pushed forward, keeps pointing at the eof marker.

21 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

22 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

23 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

24 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.4Figure 9.4 Read lines from a file Scan the line for specified string of text If text found, display message

25 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.5Figure 9.5 Read through values, calculate the average Then go back through file to find deviations from the average

26 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

27 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 of ios_base::goodbit, ios_base::badbit, ios_base::failbit, or ios_base::eofbit ).

28 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 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)

29 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 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 )

30 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 it To “unread” the last char that was read, the libraries provide: unget() // unread char most recently read

31 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

32 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

33 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 Example cout << "\nTotal cost = $" << fixed << showpoint << setprecision(2) << cost << endl;

34 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.7Figure 9.7

35 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

36 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

37 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 tables Further information www.oracle.com www.sybase.com

38 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.8Figure 9.8

39 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.9Figure 9.9 Driver to test converter operations, Figure 9.10Figure 9.10

40 C++ An Introduction to Computing, 3rd ed. 40 Converter Methods Sphere object converter, Figure 9.11Figure 9.11 Driver, Figure 9.12Figure 9.12 Converts from a Sphere to a string Converts from a Sphere to a string


Download ppt "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."

Similar presentations


Ads by Google