WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files Prof. - - PowerPoint PPT Presentation

with c
SMART_READER_LITE
LIVE PREVIEW

WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files Prof. - - PowerPoint PPT Presentation

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


slide-1
SLIDE 1
  • Prof. amr Goneid, AUC

1

CSCE 110 PROGRAMMING FUNDAMENTALS

WITH C++

  • Prof. Amr Goneid

AUC Part 9. Streams & Files

slide-2
SLIDE 2
  • Prof. amr Goneid, AUC

2

Streams & Files

slide-3
SLIDE 3
  • 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

slide-4
SLIDE 4
  • 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, HD etc)

 A file on HD is associated with a stream

slide-5
SLIDE 5
  • Prof. amr Goneid, AUC

5

Streams and Files

Memory Device Device Device FILES streams

slide-6
SLIDE 6
  • Prof. amr Goneid, AUC

6

Extraction Operator

Extracts sequence

  • f

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

Memory >> Input Device

slide-7
SLIDE 7
  • Prof. amr Goneid, AUC

7

Insertion Operator

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

<< Output Device Memory

slide-8
SLIDE 8
  • 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.

slide-9
SLIDE 9
  • Prof. amr Goneid, AUC

9

Default Streams

Memory variable x screen keyboard FILES input stream cin >> x; cout << x;

  • utput stream
slide-10
SLIDE 10
  • 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 , ‘ * ’)

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

slide-12
SLIDE 12
  • Prof. amr Goneid, AUC

12

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 }

slide-13
SLIDE 13
  • 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"

slide-14
SLIDE 14
  • Prof. amr Goneid, AUC

14

CountChars.cpp

int main() { const char NWLN = '\n'; // newline character char next; int charCount; int totalChars; int lineCount; lineCount = 0; totalChars = 0;

slide-15
SLIDE 15
  • Prof. amr Goneid, AUC

15

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

slide-16
SLIDE 16
  • Prof. amr Goneid, AUC

16

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;

slide-17
SLIDE 17
  • Prof. amr Goneid, AUC

17

CountChars.cpp

cout << "Total number of characters is " << totalChars << endl; return 0; }

slide-18
SLIDE 18
  • 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

slide-19
SLIDE 19
  • 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

EOF FP

slide-20
SLIDE 20
  • 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 EOF EOLN character

slide-21
SLIDE 21
  • 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:

  • fstream <internal name>;

e.g.

  • fstream target;

 C++ uses internal name for I/O operations

  • 6. Declaring Streams
slide-22
SLIDE 22
  • 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;

slide-23
SLIDE 23
  • 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

slide-24
SLIDE 24
  • 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

  • utput files if we change the filename

Opening and Closing

slide-25
SLIDE 25
  • 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”;

  • fstream target;

target.open(filename.c_str());

Opening and Closing

slide-26
SLIDE 26
  • 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();

slide-27
SLIDE 27
  • 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

  • pen

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

slide-28
SLIDE 28
  • 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;

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

slide-29
SLIDE 29
  • 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()

slide-30
SLIDE 30
  • 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);

slide-31
SLIDE 31
  • 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;

slide-32
SLIDE 32
  • 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 blanks target << m << “ “ << n << “ “ << x << “ “; // To read them: source >> m >> n >> x ;

slide-33
SLIDE 33
  • Prof. amr Goneid, AUC

33

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

slide-34
SLIDE 34
  • Prof. amr Goneid, AUC

34

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

slide-35
SLIDE 35
  • 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 ,

  • fstream& target);
slide-36
SLIDE 36
  • 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)

slide-37
SLIDE 37
  • 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;

  • fstream 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(); }

slide-38
SLIDE 38
  • 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); }