Lecture 27: File Input/Output Processing. 2 Lecture Contents: t Input/Output files t Text files and...

Post on 18-Jan-2018

237 views 0 download

description

3 File basics File definition: Collection of related information stored on a disk. t File may contain the source text of a C++ program. t File may contain data to be processed (input data file). t File may contain results generated by a program (output data file).

Transcript of Lecture 27: File Input/Output Processing. 2 Lecture Contents: t Input/Output files t Text files and...

Lecture 27: File Input/Output Processing

2

Lecture Contents:

Input/Output files Text files and Binary files File access Standard Input/Output Demo programs Exercises

3

File basics

File definition: Collection of related information stored on a disk.

File may contain the source text of a C++ program. File may contain data to be processed (input data

file). File may contain results generated by a program

(output data file).

4

File classification

- Text mode files

- Binary mode files

5

File classification

Text mode filesA named collection of characters saved on a disk having the

following structure:

<line1> nl <line2> nl … <linen> nl eof

The newline character nl(‘\n’) partitions a file or a stream into a sequence of lines/records. Each line/record is a sequence of characters. This is called logical partition.

The eof indicates the physical end of the file.

6

File classification

Text mode filesA common way to store data in a text file is to place

each record on a single line with the fields separated by commas. This design is known as CSV format (Comma Separated Values).

Example:Barbara,1942Deborah,1940Julia,1945

7

File classificationText mode files

An alternate design of text file is known as LSV format (Line Separated Values) where each field is placed on a single line.

Example:Barbara1942Deborah1940Julia1945

8

File classification

Binary mode filesA file containing binary numbers that are the

computer’s internal representation of each file component.

9

Input/Output stream

I/O stream – continuous sequence of character codes representing textual input(output) data.

I/O stream – sequence of characters for program input or for program output

C++ (supported by #include <iostream>)Standard input stream: cinStandard output stream: cout

C (supported by #include <stdio.h>)Standard file pointer for keyboard input: stdinSystem file pointer for screen output: stdout

10

Input/Output stream

I/O stream – an abstraction intended to serveas a handle or

as a link, oras a connection, oras a binding between

the physically existing external file andthe program that intends to operate on it.

11

Input/Output stream

Three activities must perform in order to implement effective I/O processing:

Open file. To establish connection btw stream defined in program and external file.

Read/Write data. Essential I/O processing.

Close file. To destroy connection established during file opening.

12

No I/O statements in C. I/O based on run time functions

Open a file fopen( )================================================

Input/Output processing (reading/writing data) Text mode filesGeneral I/O streams: putc(), getc( )fputs( ), fgets( )fprintf( ), fscanf( )Standard I/O streams: putchar( ), getchar( )puts( ), gets( )printf( ), scanf( ) Binary mode filesfwrite( ), fread( )

================================================Close a file fclose( ), fcloseall( )

13

No I/O statements in C++. I/O based on OO streams:

Before we can read or write an external file in a program, we must first declare a stream object for each stream/file to be processed by our program. Declarations #include <fstream>ifstream inf; ofstream outf;

involve two new data types:ifstream (input file stream) and ofstream (output file stream).

Once the stream objects have been declared, we can open the files:inf.open(“Test.txt”); outf.open(“Test1.txt”);

After the files are opened, real input/output activities may be processed.inf >> . . . ; outf << . . . ;

After all input/output is done, files must be closed:inf.close(); outf.close();

14

No I/O statements in C++. I/O based on OO streams:

Before we can read or write an external file in a program, we must first declare a stream object for each stream/file to be processed by our program. Declarations

#include <fstream>ifstream inf; ofstream outf;

involve two new data types: ifstream (input file stream) and ofstream (output file stream).

15

No I/O statements in C++. I/O based on OO streams:

Once the stream objects have been declared, we can open the files:

inf.open(“Test.txt”);

outf.open(“Test1.txt”);

16

No I/O statements in C++. I/O based on OO streams:

After the files are opened, efective input/output activities may be processed.

inf >> . . . ; // extract from input stream

outf << . . . ; // insert into output stream

17

No I/O statements in C++. I/O based on OO streams:

After all input/output is done, files must be closed:

inf.close();

outf.close();

18

No I/O statements in C++. I/O based on OO streams:

fs.open(fname) Opens stream fs for input or output. Connects the stream fs to the external file fname.

fs.get(ch)Extracts the external char from input stream fs and places it into var ch

fs.put(ch)Inserts (writes or displays) char ch into stream fs. fs.close() Disconnects stream fs from associated external file. fs.eof() Tests for end-of-file condition on stream fs fs.fail() Returns true if an operation on stream fs, such as open

failed to execute properly.

19

Demo programs illustrating different versions of end-of-file controlled loop reading characters from keyboard and copying them on the screen

// file probaf1.cpp#include <iostream>using namespace std;void main(){ char ch; while ( !cin.eof() ) { cin.get(ch); cout << "\n>>>>>>>>>>>> " << ch; }}

20

Demo programs illustrating different versions of end-of-file controlled loop reading characters from keyboard and copying them on the screen

// file probaf2.cpp#include <iostream>using namespace std;void main(){ char ch; while ( cin ) { cin.get(ch); cout << "\n>>>>>>>>>>>> " << ch; }}

21

Demo programs illustrating different versions of end-of-file controlled loop reading characters from keyboard and copying them on the screen

// file probaf3.cpp#include <iostream>using namespace std;void main(){ char ch; while ( cin.get(ch)!= 0 ) {

cout << "\n>>>> " << ch; }}

22

Demo program how to create output file test.txt

// file probaf4.cpp#include <fstream>using namespace std;void main(){ char *t1 = "Sofia - Capital city of BULGARIA\n"; char *t2 = “Berlin - Capital city of GERMANY\n"; ofstream outf; outf.open("TEST.TXT", ios::out);  outf << t1; outf << t2;  outf.close();}

23

Demo program illustrating how to read the same file “Test.txt” (created by demo probaf4.exe) using 3 different end-of-file controlled loops (same style as the first demo presented)

// file probaf5.cpp#include <fstream>using namespace std;void main(){ char ch; ifstream inf; inf.open(“TEST.TXT”, ios::in); while ( !inf.eof() ) {

inf.get(ch); cout << ch; } inf.close();}

24

Demo program illustrating how to read the same file “Test.txt” (created by demo probaf4.exe) using 3 different end-of-file controlled loops (same style as the first demo presented)

// file probaf6.cpp // ‘ ‘ space serves as a separator#include <fstream>using namespace std;void main(){ char ch; char tin[80]; ifstream inf; inf.open(“TEST.TXT”, ios::in); while ( inf ) {

inf >> tin; cout << tin; } inf.close();}

25

Demo program illustrating how to read the same file “Test.txt” (created by demo probaf4.exe) using 3 different end-of-file controlled loops (same style as the first demo presented)

// file probaf6a.cpp#include <fstream>#include <iostream>using namespace std;void main(){

char ch; char tin[80]; ifstream inf;inf.open("TEST.txt");while ( inf ){ // reading file line by line into C style stringinf.getline(tin,80,'\n');

cout << endl << tin;}inf.close();

}

26

Demo program illustrating how to read the same file “Test.txt” (created by demo probaf4.exe) using 3 different end-of-file controlled loops (same style as the first demo presented)

// file probaf6b.cpp#include <fstream>#include <iostream>#include <string>using namespace std;void main(){

char ch; string tin; ifstream inf;inf.open("TEST.txt");while ( inf ){// reading file line by line into C++ STL style stringgetline(inf,tin,'\n');

cout << endl << tin;}inf.close();

}

27

Demo program illustrating how to read the same file “Test.txt” (created by demo probaf4.exe) using 3 different end-of-file controlled loops (same style as the first demo presented)

// file probaf7.cpp#include <fstream>using namespace std;void main(){ char ch; char tin[80]; ifstream inf; inf.open(“TEST.TXT”, ios::in); while ( inf.get(ch)!=0 ) { cout << ch; } inf.close();}

28

Demo program illustrating how to create an output file and to read it from same program

// file probaf8.cpp#include <fstream>using namespace std;void main(){

char ch; ofstream outf; ifstream inf;  outf.open("TEST1.TXT", ios::out);  for (ch=‘ ‘; ch<= ‘z’; ch++) outf.put(ch);  outf.close(); cout << "\n\n\nPause\n\n"; inf.open("TEST1.TXT", ios::in); while ( inf )

{ inf.get(ch); cout << ch; } inf.close();}

29

Demo program illustrating how to create output file containing data for objects of user defined class Person

// file probaf11.cpp

See handout page 4 for details

30

More on files

Extract from Friedman/Koffman, chapter 8

Streams, Files, and Formatting

Chapter 8

32

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

33

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

34

Reading Data >>

When reading data from a stream using >>, any leading white space (‘ ‘, ‘\t’, ‘\n’) is skipped until the first non-white space character is found. This is the case when reading data into predefined data types char, int, float, bool, double, or into type string objectcin >> ch;

Also read character plus white space as a characterget and put functions

35

Reading one Character at a time

Function get is used to read one character at a time.

Function put is used to display one character at a time.

The following program processes individual characters in a stream

36

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“int main(){ const char NWLN = '\n'; // newline character

char next; int charCount;

int totalChars = 0; int lineCount = 0;

37

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

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

38

CountChars.cpp

cout << “\n\nNumber of lines processed is " << lineCount << endl; cout << "Total number of characters is " <<

totalChars << endl; return 0;}

39

8.2 External Files

Interactive– Interactive programs read their input from the cin

stream associated with the keyboard and they display their output to the cout stream associated with a display

Batch– After a data file is saved on disk, you can instruct your

program to read data from the file rather than from the keyboard or to write its output to a disk rather than to display on the screen. This mode of execution is called batch processing.

40

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

41

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> class

42

Files

Declare the stream to be processed need to #include <fstream>ifstreamins; // input streamofstream outs; // output stream

Need to open the filesins.open(inFile);outs.open(outFile);

43

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

44

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"

45

CopyFile.cpp

// Functions used ...// Copies one line of textint copyLine(ifstream&, ofstream&);

int main(){

// Local data ... int lineCount; ifstream ins; ofstream outs;

46

CopyFile.cpp

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

outs.open(outFile); if (outs.fail()) { cerr << "*** ERROR: Cannot open " << outFile ; return EXIT_FAILURE;// failure return } // end if

47

CopyFile.cpp

// Copy each character from inData to outData. lineCount = 0; do { if (copyLine(ins, outs) != 0) lineCount++; } while (!ins.eof());

// Display a message on the screen. cout << "Input file copied to output file.\n"; cout << lineCount << " lines copied.\n" ; ins.close(); outs.close(); return 0; // successful return}

48

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 char processed from ins is <nwln>;// The last char written to outs is <nwln>.// Returns: The number of characters copied.int copyLine (ifstream& ins, ofstream& outs){ // Local data ... const char NWLN = '\n';

char nextCh; int charCount = 0;

49

CopyFile.cpp

// Copy all data chars from stream ins to stream outs. ins.get(nextCh); while ((nextCh != NWLN) && !ins.eof()) { outs.put(nextCh); charCount++; 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

50

CopyFile.cpp

Program Output

Input file copied to output file.37 lines copied.

51

Using getline with a file stream

Instead of writing own function copyline, you can use function getline to read each line of the file stream

into a string object string line; linecount = 0; getline(ins, line); while (line.length() != 0) { linecount++;

getline(ins, line);}

52

File Processing

Loop processing– for loops– while loops

Newline character– eof() function returns a False if file is not emptywhile ( ! ins.eof()){

do stuff}

53

Program Style: Reading a File Name

In previous programs, file name specified in #define – #define inFile “Indata.txt”– ins.open(inFile);

Sometimes, user needs to enter interactively file name – string filename;– cout<<“Enter fname:”: cin>>filename;– ins.open(filename.c_str() );

c_str() converts the string in filename to a C-style string which has a different format than a C++ string. The open statement has a C-style string as an argument

54

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

55

Payroll Case Structure Chart

P re pa refi les

P roce ss a lle m p lo yees

D isp layp ay ro ll

W r i te thep ayro ll f i le

processEmp

56

ProcessEmp Structure Chart

R e ad e m p loy eefirs t a n d la st

n a m es

R e ad e m p loyeesa la ry d a ta (h ou rs

a n d ra te )

C o m p u tesa la ry

A ddsa la ry to

to ta l p ay ro ll

W r i te f ir sta n d la st n am es

a nd sa la ry

P roce ss a lle m p lo yees

57

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;

58

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 TOTALmoney processEmp(istream&, ostream&);

int main(){ ifstream eds; ofstream pds; money totalPayroll;

59

Payroll.cpp

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

cerr << "***ERROR: Cannot open " << outFile ; eds.close(); return EXIT_FAILURE; // failure return }

60

Payroll.cpp

// Process all employees and compute total payroll. totalPayroll = processEmp(cin, cout);

// Display result. cout << "Total payroll is " << totalPayroll <<‘\n’;

// Close files.

eds.close(); pds.close(); return 0;}

61

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 payrollmoney processEmp (istream& eds, ostream& pds){

62

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;

63

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

64

PayrollFile.cpp

Program Output

Total payroll is $677.38

65

8.4 More on Reading String Data

Getline - could be used to process an entire line of data

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

Advance the newlinegetline (eds, name, ‘\n’);

Use care when choosing cin, get or getline

66

8.4 More on Using getline

getline(istream& ins, string& str)– Reads all chars from ins up to the first newline into

string str. The newline char extracted but not stored. getline(istream& ins, string& str, char delimiter)

– Reads all chars from ins up to the first occurrence of delimiter into string str. Delimiter extracted but not stored.

ins.ignore(int n, char delimiter)– Extract (but not store) up to n chars from ins through

the first occurrence of the delimiter char.

67

Input/output manipulators

endl Inserts the newline character into an output stream.

setw(n) Controls the width of an output field. dec, hex, oct Controls the numeric system base (10, 16, 8)

used to display values. fixed, scientific Causes real numbers to display in decimal

or in scientific notation. showpoint Ensures decimal point and trailing zeros if

necessary always to appear setprecision(n) Sets the precision to n decimal places. left, right Left-adjust or right-adjust output in field.

68

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

69

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

70

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

71

Exercise 27.1

Build programs to illustrate file I/O processingWrite programs to create(write) and read files using the

following couples of functions:Text modeCharacter I/O: putc( ), getc( )String I/O: fputs( ), fgets( )Formatted I/O: fprintf( ), fscanf( )Binary modefwrite( ), fread( )Demo programs: IOFile1.cpp, IOFile2.cpp.

72

Before lecture end

Lecture:File Input/Output processing

More to read:Friedman/Koffman, Chapter 08

73

Thank You For

Your Attention!