CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files Prof. amr Goneid, AUC 1
Streams & Files Prof. amr Goneid, AUC 2
Streams & Files What are Streams and Files? Default I/O Streams I/O Manipulators External Files Structure of Text Files Declaring Streams Opening & Closing One-Character I/O String & Data I/O Passing Files as Parameters Prof. amr Goneid, AUC 3
1. What are Streams and Files? A stream is a sequence of characters A stream has no fixed size A stream is an object that is to be declared A stream associates its sequence with an external device (e.g. keyboard, screen, HD etc) A file on HD is associated with a stream Prof. amr Goneid, AUC 4
Streams and Files FILES streams Device Memory Device Device Prof. amr Goneid, AUC 5
Extraction Operator Extracts sequence of characters from input stream and converts them to internal representation, skips leading blanks >> Memory Input Device Prof. amr Goneid, AUC 6
Insertion Operator Converts internal representation to a sequence of characters and inserts them into the output stream in the proper format << Output Memory Device Prof. amr Goneid, AUC 7
2. Default I/O Streams cin and cout are stream objects defined in the library <iostream> cin (Consol Input) is associated with the default input device (keyboard) Extraction operator ( >> ) with cin. cout (Consol Output) is associated with the default output device (screen) Insertion operator ( << ) with cout. Prof. amr Goneid, AUC 8
Default Streams FILES input stream keyboard cin >> x; Memory variable x output stream screen cout << x; Prof. amr Goneid, AUC 9
Default Streams Library #include <iostream> I/O of simple quantities: int x; string Line; cin >> x; cout << “Hello”; getline (cin , Line); getline (cin , Line , ‘ * ’) Prof. amr Goneid, AUC 10
Default Streams Library Member functions for cin and cout can be used to input/output one character at a time (including blanks and NWLN): char c; cin.get(c); // Extract next character to c // Returns 0 in case of EOF cin.eof() // Test for EOF (CTRL-Z) cout.put(c) // Insert contents of c to screen Prof. amr Goneid, AUC 11
Default Streams Library Example: char c; cin.get(c); // Extract character to c while ( ! cin.eof() ) // Test for EOF (CTRL-Z) { c = toupper (c); // Convert to uppercase cout.put(c) // Insert contents of c to screen cin.get(c); // Get next character } Prof. amr Goneid, AUC 12
Example: 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" Prof. amr Goneid, AUC 13
CountChars.cpp int main() { const char NWLN = '\n'; // newline character char next; int charCount; int totalChars; int lineCount; lineCount = 0; totalChars = 0; Prof. amr Goneid, AUC 14
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 Prof. amr Goneid, AUC 15
CountChars.cpp cout.put(NWLN); lineCount++; cout << "Number of characters in line " << lineCount << " is " << charCount << endl; cout << "Enter a line or press " << ENDFILE << ": "; } // end outer while cout << endl << endl << "Number of lines processed is " << lineCount << endl; Prof. amr Goneid, AUC 16
CountChars.cpp cout << "Total number of characters is " << totalChars << endl; return 0; } Prof. amr Goneid, AUC 17
3. I/O Manipulators #include <iomanip> when using setw (int n) and width (int n) setprecision (int n) boolalpha fixed & scientific left & right Prof. amr Goneid, AUC 18
4. External Files External stream objects Used to read from or write to. Elements with a File Pointer (FP) and an EOF. element EOF FP Prof. amr Goneid, AUC 19
5. Structure of Text Files Elements are single character or strings with EOLN Access is Sequential Opened in a Single Mode (input or output but not both). Mode can be changed after closing the file. FP character EOF Line EOLN EOF FP Prof. amr Goneid, AUC 20
6. Declaring Streams Use #include <fstream> for external text file stream objects. It provides two data types: ifstream for input files, ofstream for output files To declare an input file stream: ifstream <internal name>; e.g. ifstream source; To declare an output file stream: ofstream <internal name>; e.g. ofstream target; C++ uses internal name for I/O operations Prof. amr Goneid, AUC 21
7. Opening and Closing To access a disk file, we have to associate it with a stream. We do this through the .open function. A file has a DOS name that can be saved in a string, e.g. string filename = “c:\data.txt”; or read the name from the keyboard, e.g. string filename; cin >> filename; Prof. amr Goneid, AUC 22
Opening and Closing To open the file for input only: source.open(filename); Resets FP to the beginning. source can be associated with other input files if we change the filename. Prof. amr Goneid, AUC 23
Opening and Closing To open the file for output only: target.open(filename); Creates a new file for writing or erases an already existing file. Resets FP to the beginning. target can be associated with other output files if we change the filename Prof. amr Goneid, AUC 24
Opening and Closing Some compilers do not support string parameters to the open/close file function. In this case, we convert the filename string to a standard C character array, e.g. string filename = “c:\data.txt”; ofstream target; target.open(filename.c_str()); Prof. amr Goneid, AUC 25
Opening and Closing To close opened files: source.close(); target.close(); After closing a file, you can use the stream again with another file. Prof. amr Goneid, AUC 26
Opening and Closing You can test if a file opened correctly. The .fail() function gives a no-zero value if the file fails to open source.fail() or target.fail() Example: source.open(inFile.c_str()); if (source.fail ()) { cerr << "*** ERROR: Cannot open " << inFile << endl; return 1 // failure return } // end if Prof. amr Goneid, AUC 27
Example /* Declare two streams, one for input, the other for output. Attach them to two physical files, e.g. “data1.txt” and “data2.txt” */ #include <iostream> #include <fstream> string infile , outfile; ifstream source; ofstream target; cout << “Enter Input File Name: “; cin >> infile; cout << “Enter Output File Name: “; cin >> outfile; source.open ( infile.c_str() ); target.open (outfile.c_str() ); Prof. amr Goneid, AUC 28
8. One Character I/O To read character by character : char c; source.get(c); Advances FP to next character To test for EOF: source.eof() Prof. amr Goneid, AUC 29
One Character I/O To write character by character : char c; target.put(c); Advances FP to next character location Prof. amr Goneid, AUC 30
9. String & Data I/O // To read a whole line (including blanks) and // terminated by NWLN: string line; getline(source,line); // To read a string terminated by blank: source >> line; // in the style of cin >> line // To skip over next n characters: source.ignore(n); or source.ignore(n , ‘\n’); // To write a string followed by NWLN: target << line << endl; Prof. amr Goneid, AUC 31
Data I/O Numeric Data can also be written to and read from text files, e.g. int m = 20; int n = 300; float x = 1.345; // Write them separated by blanks target << m << “ “ << n << “ “ << x << “ “; // To read them: source >> m >> n >> x ; Prof. amr Goneid, AUC 32
Data I/O Some other member functions of input streams: input_stream.peek(ch); // look ahead one char input_stream.unget(); // put the last char back Prof. amr Goneid, AUC 33
Data I/O The following code segment will read one integer number from a file. char ch; int number ifstream source; source.open(“mydata”); source.get(ch); // get one character if (isdigit(ch)) { source.unget(); source >> number; } source.close(); Prof. amr Goneid, AUC 34
10. Passing Files as Parameters The declarations : ifstream source; ofstream target; declare source & target as “pointers” to the file stream objects. If they are parameters to or from functions, they should be passed by their address, e.g. int copyline (ifstream& source , ofstream& target); Prof. amr Goneid, AUC 35
Recommend
More recommend