28
Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551 [email protected]

Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

Embed Size (px)

Citation preview

Page 1: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

Chapter 8

Streams and Files

Lecture Notes Prepared By:

Blaise W. Liffick, PhDDepartment of Computer ScienceMillersville UniversityMillersville, PA [email protected]

Page 2: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-2

8.1 Standard Input/Output Streams• A stream is a sequence of characters• Standard input stream (cin) and standard output

stream (cout) of the iostream library • Streams convert internal representations to

character streams or vice versa• >> input (extraction) operator• << output (insertion) operator• Any character (printable or not)• A stream has no fixed size

Page 3: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-3

Input Stream, >> Operator

• Last character read is kept track using an input stream buffer pointer

• Each new input attempt begins at current pointer position

• Leading white space (blanks, tab, nwln) skipped until first non-white-space character is located

cin >> ch;

• For numeric value, all characters that are part of the numeric value are processed until a character that’s not legally part of a C++ number is read.

Page 4: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-4

Reading One Character at a Time

• Can also read/write white space– iostream functions get and put

Page 5: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-5

Listing 8.2 Processing individual characters in a stream

Page 6: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-6

Listing 8.2 Processing individual characters in a stream (continued)

Page 7: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-7

Table 8.1 The File Manipulation Member Functions

Page 8: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-8

Using a Stream in a Condition

cout << “Enter a line or press “ << ENDFILE << “: “;

while (cin.get(next)) // get first char of new line

{

// insert loop body including inner while loop

. . .

cout << “Enter a line or press “ << ENDFILE << “: “;

} // end outer while

Page 9: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-9

8.2 External Files• Interactive

– Expect user input from keyboard

– Ok for smaller programs

• Batch– Requires use of data files (save to disk)

– Don’t expect input from keyboard, so no prompts

– Often uses echo printing of input

– Input file can be read many times

– Can also write output to file

– Output file from one program can be input to another

Page 10: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-10

Directory Names for External Files

• Must know location of file within directory structure (pathname)

• Directories are system dependent

• File names usually follow system and local conventions– how file is named– use of extensions

• .cpp .dat .doc .txt

Page 11: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-11

Attaching Streams to External Files

• Declaring a stream object

ifstream ins;

ofstream outs;

• External (physical) file name linked to internal (logical) name by open function

#define inFile “InData.txt”. . .

ins.open(inFile);

Page 12: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-12

Reading a File Name

string fileName;

cout << “Enter the input file name: “;

cin >> fileName;

ins.open(fileName.c_str( ));

Page 13: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-13

Case Study: Preparing a Payroll File

• Write a program that reads a data file consisting of employee salary data, and computes the employee’s gross salary. It writes the employee’s name and gross salary to an output file and accumulates the gross salary amount in the total company payroll, which it also displays.

Page 14: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-14

Case Study: Sample Files

• Input

Jim Baxter 35.5 7.25<nwln>

Adrian Cybriwsky 40.0 6.50<nwln>

Ayisha Mertens 20.0 8.00<nwln>

• Output

Jim Baxter 257.38<nwln>

Adrian Cybriwsky 260.00<nwln>

Ayisha Mertens 160.00<nwln><eof>

Page 15: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-15

Case Study: Problem Analysis

• Streams Used– ifstream eds // employee data info– ofstream pds // payroll data info

• Problem Input (from stream eds)– for each employee

• string firstName

• string lastName

• float hoursWorked

• float hourlyRate

Page 16: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-16

Case Study: Problem Analysis

• Problem Output (to stream pds)– for each employee

• string firstName

• string lastName

• float salary

• Problem Output (to stream cout)– float totalPayroll // total company payroll

Page 17: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-17

Case Study: Program Design

• Algorithm for function main

1. Prepare streams and associated files for processing

2. Process all employees and compute payroll total (function processEmp).

3. Display the payroll total.

Page 18: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-18

Case Study: Interface for processEmp

• Input Arguments– ifstream eds // input stream - employee data– ofstream pds// output stream - payroll data

• Output Arguments– none

• Function Return Value– float totalPayroll // total company payroll

Page 19: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-19

Case Study: Algorithm for processEmp

1. Initialize payroll total to 0.0

2. While there are more employees

2.1 Read employee’s first and last names and salary data from eds

2.2 Compute employee’s salary

2.3 Write employee’s first and last names and salary to pds; add it to payroll total

Page 20: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-20

Listing 8.5 Implementation of processEmp

Page 21: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-21

Listing 8.5 Implementation of processEmp (continued)

Page 22: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-22

8.4 More on Reading String Data

• getline (istream& ins, string& str)

• getline (istream& ins, string& str, char delimiter)

• ins.ignore (int n, char delimiter)

Page 23: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-23

Using getline

• getline - could be used to process an entire line of data

• E.g. for data file containingJim Andrew Baxter# 35.5 7.25<nwln>

Adrian Cybriwsky# 40.0 6.50<nwln>

Ayisha W. Mertens# 20.0 8.00<nwln>

• Use # as a delimiter charactergetline (eds, name, ‘#’);

Page 24: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-24

Using ignore

• getline does not skip leading white space, so if a newline character is encountered at the beginning of the characters to be extracted, getline will stop immediately and won’t perform the expected task

• E.g. data file contains

Jim Andrew Baxter<nwln>

35.5 7.25<nwln>

Adrian Cybriwsky <nwln>

40.0 6.50 <nwln>

Page 25: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-25

payroll = 0.0;

getline(eds, name);

while (!eds.eof( ))

{

eds >> hours >> rate;

salary = hours * rate;

pds << name << “ “ << salary << endl;

payroll += salary;

eds.ignore(100, ‘\n’);

getline(eds, name);

}

Page 26: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-26

Table 8.3 Input/Output Manipulators

Page 27: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-27

Manipulators Example

cout << “The value of x is “

<< fixed

<< showpoint

<< setprecision(4) << x << endl;

Page 28: Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA 17551

© 2004 Pearson Addison-Wesley. All rights reserved 8-28

8.6 Common Programming Errors

• Connecting streams and external files

• Using input and output streams incorrectly

• Reading past the end of a file

• Matching data in an input stream to input data stores

• White space and input

• Proper handling of the newline character

• Input and output settings