38
Prof. amr Goneid, AUC 1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files

CSCI 110 STRUCTURED PROGRAMMING WITH C++rafea/CSCE110/Slides/9. Streams.pdf · PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files. Prof. amr Goneid, AUC

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Prof. amr Goneid, AUC 1

CSCE 110PROGRAMMING FUNDAMENTALS

WITH C++

Prof. Amr GoneidAUC

Part 9. Streams & Files

Prof. amr Goneid, AUC 2

Streams & Files

Prof. amr Goneid, AUC 3

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 4

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, HDetc)

A file on HD is associated with a stream

Prof. amr Goneid, AUC 5

Streams and Files

Memory

Device

Device

Device

FILES

streams

Prof. amr Goneid, AUC 6

Extraction Operator

Extracts sequence of characters frominput stream and converts them to internalrepresentation, skips leading blanks

Memory

>>

InputDevice

Prof. amr Goneid, AUC 7

Insertion Operator

Converts internal representation to asequence of characters and inserts theminto the output stream in the proper format

<<OutputDevice

Memory

Prof. amr Goneid, AUC 8

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 9

Default Streams

Memory variable x

screen

keyboard

FILES

input stream

cin >> x;

cout << x;

output stream

Prof. amr Goneid, AUC 10

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 11

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 EOFcin.eof() // Test for EOF (CTRL-Z)cout.put(c) // Insert contents of c to screen

Prof. amr Goneid, AUC 12

Default Streams Library

Example:char c;cin.get(c); // Extract character to cwhile ( ! cin.eof() ) // Test for EOF (CTRL-Z){

c = toupper (c); // Convert to uppercasecout.put(c) // Insert contents of c to screencin.get(c); // Get next character

}

Prof. amr Goneid, AUC 13

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 14

CountChars.cppint main(){

const char NWLN = '\n'; // newline character

char next; int charCount; int totalChars; int lineCount;

lineCount = 0;totalChars = 0;

Prof. amr Goneid, AUC 15

CountChars.cppcout << "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 16

CountChars.cppcout.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 17

CountChars.cpp

cout << "Total number of characters is " <<totalChars << endl;

return 0;}

Prof. amr Goneid, AUC 18

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 19

4. External Files

External stream objects Used to read from or write to. Elements with a File Pointer (FP) and

an EOF.

element

EOFFP

Prof. amr Goneid, AUC 20

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

FP

EOF

EOFEOLN

character

Prof. amr Goneid, AUC 21

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

6. Declaring Streams

Prof. amr Goneid, AUC 22

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 23

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

Prof. amr Goneid, AUC 24

To open the file for output only:target.open(filename);

Creates a new file for writing or erases analready existing file. Resets FP to thebeginning.

target can be associated with other output files if we change the filename

Opening and Closing

Prof. amr Goneid, AUC 25

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

Prof. amr Goneid, AUC 26

To close opened files:

After closing a file, you can use the stream again with another file.

Opening and Closing

source.close();target.close();

Prof. amr Goneid, AUC 27

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()

Prof. amr Goneid, AUC 28

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 29

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()

Prof. amr Goneid, AUC 30

To write character by character:

Advances FP to next character location

One Character I/O

char c;target.put(c);

Prof. amr Goneid, AUC 31

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 32

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 blankstarget << m << “ “ << n << “ “ << x << “ “;

// To read them:source >> m >> n >> x ;

Prof. amr Goneid, AUC 33

Data I/OSome other member functions of inputstreams:

input_stream.peek(ch); // look ahead one char

input_stream.unget(); // put the last char back

Prof. amr Goneid, AUC 34

Data I/OThe following code segment will read oneinteger number from a file.char ch; int numberifstream source;source.open(“mydata”);source.get(ch); // get one characterif (isdigit(ch))

{source.unget();source >> number;

}source.close();

Prof. amr Goneid, AUC 35

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 36

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)

Prof. amr Goneid, AUC 37

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();

}

Prof. amr Goneid, AUC 38

A Main to call copychar/* A main function to drive copychar */#include <iostream>#include <fstream>void copychar (string , string );int main(){

string infile , outfile;cout << “Enter Input File Name: “; cin >> infile;cout << “Enter Output File Name: “; cin >> outfile;copychar (infile,outfile);

}