Download presentation
Presentation is loading. Please wait.
Published byVirgil Moore Modified over 9 years ago
1
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files
2
Prof. amr Goneid, AUC2 Streams & Files
3
Prof. amr Goneid, AUC3 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
4
Prof. amr Goneid, AUC4 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
5
Prof. amr Goneid, AUC5 Streams and Files Memory Device FILES streams
6
Prof. amr Goneid, AUC6 Extraction Operator Extracts sequence of characters from input stream and converts them to internal representation, skips leading blanks Memory >> Input Device
7
Prof. amr Goneid, AUC7 Insertion Operator Converts internal representation to a sequence of characters and inserts them into the output stream in the proper format << Output Device Memory
8
Prof. amr Goneid, AUC8 2. Default I/O Streams cin and cout are stream objects defined in the library 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.
9
Prof. amr Goneid, AUC9 Default Streams Memory variable x screen keyboard FILES input stream cin >> x; cout << x; output stream
10
Prof. amr Goneid, AUC10 Default Streams Library #include I/O of simple quantities: int x; string Line; cin >> x; cout << “Hello”; getline (cin, Line); getline (cin, Line, ‘ * ’)
11
Prof. amr Goneid, AUC11 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
12
Prof. amr Goneid, AUC12 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 }
13
Prof. amr Goneid, AUC13 Example: CountChars.cpp // File: CountChars.cpp // Counts the number of characters and lines in // a file #include using namespace std; #define ENDFILE "CTRL-Z"
14
Prof. amr Goneid, AUC14 CountChars.cpp int main() { const char NWLN = '\n'; // newline character char next; int charCount; int totalChars; int lineCount; lineCount = 0; totalChars = 0;
15
Prof. amr Goneid, AUC15 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
16
Prof. amr Goneid, AUC16 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;
17
Prof. amr Goneid, AUC17 CountChars.cpp cout << "Total number of characters is " << totalChars << endl; return 0; }
18
Prof. amr Goneid, AUC18 3. I/O Manipulators #include when using setw (int n) and width(int n) setprecision (int n) boolalpha fixed & scientific left & right
19
Prof. amr Goneid, AUC19 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
20
Prof. amr Goneid, AUC20 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. Line FP EOF EOLN character
21
Prof. amr Goneid, AUC21 Use #include 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 ; e.g. ifstream source; To declare an output file stream: ofstream ; e.g.ofstream target; C++ uses internal name for I/O operations 6. Declaring Streams
22
Prof. amr Goneid, AUC22 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;
23
Prof. amr Goneid, AUC23 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. Opening and Closing
24
Prof. amr Goneid, AUC24 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 Opening and Closing
25
Prof. amr Goneid, AUC25 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()); Opening and Closing
26
Prof. amr Goneid, AUC26 To close opened files: After closing a file, you can use the stream again with another file. Opening and Closing source.close(); target.close();
27
Prof. amr Goneid, AUC27 You can test if a file opened correctly. The.fail() function gives a no-zero value if the file fails to open Example: source.open(inFile.c_str()); if (source.fail ()) { cerr << "*** ERROR: Cannot open " << inFile << endl; return 1// failure return } // end if Opening and Closing source.fail() or target.fail()
28
Prof. amr Goneid, AUC28 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 string infile, outfile; ifstream source; ofstream target; cout > infile; cout > outfile; source.open ( infile.c_str() ); target.open (outfile.c_str() );
29
Prof. amr Goneid, AUC29 To read character by character : Advances FP to next character To test for EOF: 8. One Character I/O char c; source.get(c); source.eof()
30
Prof. amr Goneid, AUC30 To write character by character : Advances FP to next character location One Character I/O char c; target.put(c);
31
Prof. amr Goneid, AUC31 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;
32
Prof. amr Goneid, AUC32 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 ;
33
Prof. amr Goneid, AUC33 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
34
Prof. amr Goneid, AUC34 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();
35
Prof. amr Goneid, AUC35 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);
36
Prof. amr Goneid, AUC36 Passing Files as Parameters Instead of passing streams, we may pass strings with the file names on disk and let the function do the opening and closing of the streams. For example, a function to copy a file character by character to another file would have the header: void copychar ( string infile, string outfile)
37
Prof. amr Goneid, AUC37 Function copychar /* Fuction to copy a file with a name stored in the string infile to another file with a name stored in string outfile (character by character) */ void copychar(string infile, string outfile) { char c;ifstream source; ofstream target; source.open(infile.c_str()); target.open(outfile.c_str()); source.get(c); while (! source.eof()) { target.put(c); source.get(c); } source.close();target.close(); }
38
Prof. amr Goneid, AUC38 A Main to call copychar /* A main function to drive copychar */ #include void copychar (string, string ); int main() { string infile, outfile; cout > infile; cout > outfile; copychar (infile,outfile); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.