Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lecture 27: File Input/Output Processing. 2 Lecture Contents: t Input/Output files t Text files and Binary files t File access t Standard Input/Output."— Presentation transcript:

1 Lecture 27: File Input/Output Processing

2 2 Lecture Contents: t Input/Output files t Text files and Binary files t File access t Standard Input/Output t Demo programs t Exercises

3 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).

4 4 File classification - Text mode files - Binary mode files

5 5 File classification Text mode files A named collection of characters saved on a disk having the following structure: nl nl … 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 6 File classification Text mode files A 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,1942 Deborah,1940 Julia,1945

7 7 File classification Text 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: Barbara 1942 Deborah 1940 Julia 1945

8 8 File classification Binary mode files A file containing binary numbers that are the computer’s internal representation of each file component.

9 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 ) Standard input stream: cin Standard output stream: cout C (supported by #include ) Standard file pointer for keyboard input: stdin System file pointer for screen output: stdout

10 10 Input/Output stream I/O stream – an abstraction intended to serve as a handle or as a link, or as a connection, or as a binding between the physically existing external file and the program that intends to operate on it.

11 11 Input/Output stream Three activities must perform in order to implement effective I/O processing: t Open file. To establish connection btw stream defined in program and external file. t Read/Write data. Essential I/O processing. t Close file. To destroy connection established during file opening.

12 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 files General I/O streams: putc(),getc( ) fputs( ),fgets( ) fprintf( ),fscanf( ) Standard I/O streams: putchar( ),getchar( ) puts( ),gets( ) printf( ),scanf( ) Binary mode files fwrite( ),fread( ) ================================================ Close a file fclose( ),fcloseall( )

13 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 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 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 ifstream inf;ofstream outf; involve two new data types: ifstream (input file stream) and ofstream (output file stream).

15 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 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 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 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 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 using namespace std; void main() { char ch; while ( !cin.eof() ) { cin.get(ch); cout >>>>>>>>>>> " << ch; }

20 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 using namespace std; void main() { char ch; while ( cin ) { cin.get(ch); cout >>>>>>>>>>> " << ch; }

21 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 using namespace std; void main() { char ch; while ( cin.get(ch)!= 0 ) { cout >>> " << ch; }

22 22 Demo program how to create output file test.txt // file probaf4.cpp #include 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 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 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 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 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 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 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 string inf.getline(tin,80,'\n'); cout << endl << tin; } inf.close(); }

26 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 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 string getline(inf,tin,'\n'); cout << endl << tin; } inf.close(); }

27 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 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 28 Demo program illustrating how to create an output file and to read it from same program // file probaf8.cpp #include 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 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 30 More on files Extract from Friedman/Koffman, chapter 8

31 Streams, Files, and Formatting Chapter 8

32 32 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams convert internal representations to character streams t >> input operator (extractor) t << output operator (inserter) t Streams have no fixed size

33 33 Reading Data >> t Leading white space skipped t also skipped t Until first character is located cin >> ch; t Also read character plus white space as a character –get and put functions

34 34 Reading Data >> t 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 object cin >> ch; t Also read character plus white space as a character get and put functions

35 35 Reading one Character at a time t Function get is used to read one character at a time. t Function put is used to display one character at a time. t The following program processes individual characters in a stream

36 36 CountChars.cpp // File: CountChars.cpp // Counts the number of characters and lines in a file #include 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 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 38 CountChars.cpp cout << “\n\nNumber of lines processed is " << lineCount << endl; cout << "Total number of characters is " << totalChars << endl; return 0; }

39 39 8.2 External Files t 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 t 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 40 8.2 External Files t 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 t Interactive –Real time systems –Ok for smaller programs –Programs that complete quickly

41 41 Files t Naming –.cpp.dat.out.in t How to attach files to the stream –stream object –external file name –internal name –open t Additional functions as part of class

42 42 Files t Declare the stream to be processed need to #include ifstreamins;// input stream ofstream outs;// output stream t Need to open the files ins.open(inFile); outs.open(outFile);

43 43 Files t #define associates the name of the stream with the actual file name t fail() function - returns true nonzero if file fails to open t Program CopyFile.cpp demonstrates the use of the other functions –get, put, close and eof –discuss program

44 44 CopyFile.cpp // File: CopyFile.cpp // Copies file InData.txt to file OutData.txt #include using namespace std; // Associate stream objects with external file names #define inFile "InData.txt" #define outFile "OutData.txt"

45 45 CopyFile.cpp // Functions used... // Copies one line of text int copyLine(ifstream&, ofstream&); int main() { // Local data... int lineCount; ifstream ins; ofstream outs;

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

49 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 50 CopyFile.cpp Program Output Input file copied to output file. 37 lines copied.

51 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 52 File Processing t Loop processing –for loops –while loops t Newline character –eof() function returns a False if file is not empty while ( ! ins.eof()) { do stuff }

53 53 Program Style: Reading a File Name t In previous programs, file name specified in #define –#define inFile “Indata.txt” – ins.open(inFile); t Sometimes, user needs to enter interactively file name – string filename; – cout >filename; – ins.open(filename.c_str() ); t 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 54 8.3 Using External File Functions t Payroll Case Study t Two programs process the payroll t Design Process –Problem Analysis –Program Design –Program Implementation –Program Verification and Test

55 55 Payroll Case Structure Chart processEmp

56 56 ProcessEmp Structure Chart

57 57 Payroll.cpp // File: Payroll.cpp // Creates a company employee payroll file // computes total company payroll amount #include #include "money.h" #include "money.cpp" using namespace std;

58 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 TOTAL money processEmp(istream&, ostream&); int main() { ifstream eds; ofstream pds; money totalPayroll;

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

62 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 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 64 PayrollFile.cpp Program Output Total payroll is $677.38

65 65 8.4 More on Reading String Data t Getline - could be used to process an entire line of data t Use # as a delimiter character getline (eds, name, ‘#’); t Advance the newline getline (eds, name, ‘\n’); t Use care when choosing cin, get or getline

66 66 8.4 More on Using getline t 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. t 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. t 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 67 Input/output manipulators t endlInserts the newline character into an output stream. t setw(n)Controls the width of an output field. t dec, hex, octControls the numeric system base (10, 16, 8) used to display values. t fixed, scientificCauses real numbers to display in decimal or in scientific notation. t showpointEnsures decimal point and trailing zeros if necessary always to appear t setprecision(n)Sets the precision to n decimal places. t left, rightLeft-adjust or right-adjust output in field.

68 68 8.5 Input/Output Manipulators t Chapter 5 covered setf, unsetf, precision and width t Can be used with the cout and << t Table 8.3 lists various manipulator functions (setiosflags, setprecision, setw) t #include when using t Can be used with external files like stdout and stdin

69 69 Formatting with State Flags t Depending on the setiosflags or unsetiosflags –Output can be controlled by other format state flag –Flags are enumerated types t ios::flagname t Table 8.3 lists some flags –boolalpha, fixed, left, right, showpoint etc

70 70 8.6 Common Programming Errors t Connecting streams and external files –Declare stream object and open the file t Watch use of while loops when processing –Test values see what you actually have t Reading past the eof t White space t Newline character t Formatting via flags

71 71 Exercise 27.1 Build programs to illustrate file I/O processing Write programs to create(write) and read files using the following couples of functions: Text mode Character I/O: putc( ), getc( ) String I/O: fputs( ), fgets( ) Formatted I/O: fprintf( ), fscanf( ) Binary mode fwrite( ), fread( ) Demo programs: IOFile1.cpp, IOFile2.cpp.

72 72 Before lecture end Lecture: File Input/Output processing More to read: Friedman/Koffman, Chapter 08

73 73 Thank You For Your Attention!


Download ppt "Lecture 27: File Input/Output Processing. 2 Lecture Contents: t Input/Output files t Text files and Binary files t File access t Standard Input/Output."

Similar presentations


Ads by Google