csce 110 programming fundamentals with c++

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

Upload: minya

Post on 14-Jan-2016

52 views

Category:

Documents


2 download

DESCRIPTION

CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++. Prof. Amr Goneid AUC Part 9. Streams & Files. Streams & Files. Streams & Files. What are Streams and Files? Standard I/O Streams I/O Manipulators External Files Structure of Text Files Declaration Opening & Closing One-Character I/O - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 1

CSCE 110CSCE 110PROGRAMMING FUNDAMENTALSPROGRAMMING FUNDAMENTALS

WITH WITH C++C++

Prof. Amr Goneid

AUC

Part 9. Streams & Files

Page 2: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 2

Streams & FilesStreams & Files

Page 3: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 3

Streams & FilesStreams & 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

Page 4: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 4

1. What are Streams and Files?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

Page 5: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 5

Streams and FilesStreams and Files

Memory

Device

Device

Device

FILES

streams

Page 6: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 6

Extraction OperatorExtraction Operator

Extracts sequence of characters from input stream and converts them to internal representation, skips leading blanks

Memory

>>

InputDevice

Page 7: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 7

Insertion OperatorInsertion Operator

Converts internal representation to a sequence of characters and inserts them into the output stream in the proper format

<<

OutputDevice

Memory

Page 8: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 8

2. Default I/O Streams2. 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.

Page 9: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 9

Default StreamsDefault Streams

Memory variable x

screen

keyboard

FILES

input stream

cin >> x;

cout << x;

output stream

Page 10: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 10

Default Streams LibraryDefault Streams Library

#include <iostream>

I/O of simple quantities:

int x; string Line;

cin >> x;

cout << “Hello”;

getline (cin , Line);

getline (cin , Line , ‘ * ’)

Page 11: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 11

Default Streams LibraryDefault 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

Page 12: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 12

Default Streams LibraryDefault 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

}

Page 13: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 13

Example: CountChars.cppExample: 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"

Page 14: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 14

CountChars.cppCountChars.cpp

int main()

{

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

char next;

int charCount;

int totalChars;

int lineCount;

lineCount = 0;

totalChars = 0;

Page 15: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 15

CountChars.cppCountChars.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

Page 16: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 16

CountChars.cppCountChars.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;

Page 17: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 17

CountChars.cppCountChars.cpp

cout << "Total number of characters is " <<

totalChars << endl;

return 0;

}

Page 18: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 18

3. I/O Manipulators3. I/O Manipulators

#include <iomanip> when using setw (int n) and width(int n) setprecision (int n) boolalpha fixed & scientific left & right

Page 19: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 19

4. External Files4. External Files

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

an EOF.

element

EOF

FP

Page 20: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 20

5. Structure of Text Files5. 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

Page 21: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

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 Streams6. Declaring Streams

Page 22: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 22

7. Opening and Closing7. 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;

Page 23: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

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 ClosingOpening and Closing

Page 24: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 24

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 ClosingOpening and Closing

Page 25: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

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 ClosingOpening and Closing

Page 26: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 26

To close opened files:

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

Opening and ClosingOpening and Closing

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

Page 27: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

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 ClosingOpening and Closing

source.fail() or target.fail()

Page 28: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 28

ExampleExample

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

Page 29: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 29

To read character by character:

Advances FP to next character To test for EOF:

8. One Character I/O8. One Character I/O

char c;source.get(c);

source.eof()

Page 30: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 30

To write character by character:

Advances FP to next character location

One Character I/OOne Character I/O

char c;target.put(c);

Page 31: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 31

9. String & Data I/O9. 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;

Page 32: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 32

Data I/OData 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 ;

Page 33: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 33

Data I/OData I/OSome other member functions of input

streams:

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

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

Page 34: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 34

Data I/OData I/OThe 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();

Page 35: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 35

10. Passing Files as Parameters10. 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);

Page 36: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 36

Passing Files as ParametersPassing 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)

Page 37: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 37

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

}

Page 38: CSCE 110 PROGRAMMING FUNDAMENTALS WITH  C++

Prof. amr Goneid, AUC 38

A Main to call copycharA 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);

}