Lec 47.48 - stream-files

30
Stream and Files Stream and Files Chapter: Chapter: 12 12 Lecture: 47 and 48 Lecture: 47 and 48 Date: 12.11.2012 Date: 12.11.2012

description

 

Transcript of Lec 47.48 - stream-files

Page 1: Lec 47.48 - stream-files

Stream and FilesStream and Files

Chapter: 12Chapter: 12

Lecture: 47 and 48Lecture: 47 and 48

Date: 12.11.2012Date: 12.11.2012

Page 2: Lec 47.48 - stream-files

ObjectivesObjectives Overview of stream classesOverview of stream classes

Showing how to perform file-related activities using Showing how to perform file-related activities using streams:streams: How to read and write data to files in a variety of waysHow to read and write data to files in a variety of ways How to handle files or I/O errorsHow to handle files or I/O errors How files and OOP are relatedHow files and OOP are related

Page 3: Lec 47.48 - stream-files

StreamsStreams Stream (flow of data)Stream (flow of data)

A transfer of information in the form of a sequence of bytesA transfer of information in the form of a sequence of bytes

In C++, a stream is represented by an object In C++, a stream is represented by an object of a particular class; e.g., of a particular class; e.g., cincin and and coutcout are are objects of objects of iostreamiostream class. class.

I/O Operations:I/O Operations: Input:Input: A stream that flows from an input device ( i.e.: A stream that flows from an input device ( i.e.:

keyboard, disk drive, network connection) to main memorykeyboard, disk drive, network connection) to main memory Output:Output: A stream that flows from main memory to an A stream that flows from main memory to an

output device ( i.e.: screen, printer, disk drive, network output device ( i.e.: screen, printer, disk drive, network connection)connection)

Page 4: Lec 47.48 - stream-files

MEM

CPU

HDD

keyboard

monitorterminalconsole

standard input

stream

standardoutput stream

StreamsStreams

What does information What does information travel across?travel across?

Page 5: Lec 47.48 - stream-files

MEM

CPU

HDD

keyboard

monitorterminalconsole

standard input

stream

standardoutput stream

fileinput strea

mLOADREAD file

output

stream

SAVEWRITE

StreamsStreams files

What does What does information travel information travel

across?across?

Page 6: Lec 47.48 - stream-files

C++ Stream Input/outputC++ Stream Input/output iostream library has hundreds of I/O capabilitiesiostream library has hundreds of I/O capabilities

iostreamiostream: basic input and output: basic input and output fstreamfstream: file processing: file processing

iostream library contains many I/O related iostream library contains many I/O related classes:classes: istreamistream ( the extraction operator ( the extraction operator >>, >>, andand get(), getline(), get(), getline(),

read() read() are members of this classare members of this class) ) ostreamostream (the insertion operator (the insertion operator <<, put(), write() <<, put(), write() are are

members of this classmembers of this class)) istream and ostream are subclasses of ios base istream and ostream are subclasses of ios base

classclass coutcout is a predefined object of the is a predefined object of the

iostream_withassigniostream_withassign class, whereas class, whereas cincin is a is a predefined object of predefined object of istream_withassignistream_withassign class class

Page 7: Lec 47.48 - stream-files

C++ Stream Input/outputC++ Stream Input/output

The classes used for input and output to The classes used for input and output to the video display and keyboard are the video display and keyboard are declared in the header file declared in the header file iostream, iostream, e.g.,e.g., #include <iostream>#include <iostream>

The classes used specifically for disk file The classes used specifically for disk file I/O are declared in theI/O are declared in the fstream fstream header file, header file, e.g., e.g., #include <fstream>#include <fstream>

All of them can be found in the All of them can be found in the include include subdirectory of the C++ compiler.subdirectory of the C++ compiler.

Page 8: Lec 47.48 - stream-files

Str

eam

Cla

ss

Str

eam

Cla

ss

Hie

rarc

hy

Hie

rarc

hy

Page 9: Lec 47.48 - stream-files

ios Classios Class

The granddaddy of all the stream classes, The granddaddy of all the stream classes, and contains the majority of the features and contains the majority of the features needed to operate C++ streamsneeded to operate C++ streams

Three most important features of Three most important features of iosios class are:class are:1)1) Formatting flagsFormatting flags2)2) Error-status flagsError-status flags3)3) File operation modeFile operation mode

Page 10: Lec 47.48 - stream-files

ios Formatting Flagsios Formatting Flags

The formatting flags act as on/off The formatting flags act as on/off switches that specify choices for switches that specify choices for various aspects of input and output various aspects of input and output format and operation.format and operation.

Page 11: Lec 47.48 - stream-files
Page 12: Lec 47.48 - stream-files

ios Formatting Flagsios Formatting Flags

Since they are the members of the ios Since they are the members of the ios class, they must follow the name ios class, they must follow the name ios and the scope resolution operator;and the scope resolution operator;e.g., e.g., ios::showpointios::showpoint

All the flags must be set using the setf() All the flags must be set using the setf() and usetf() ios member functions;and usetf() ios member functions;e.g., e.g., cout.setf(ios::showpoint)cout.setf(ios::showpoint) cout.unsetf(ios::showpoint)cout.unsetf(ios::showpoint)

Page 13: Lec 47.48 - stream-files

#include <iostream>#include <conio.h>using namespace std;

int main(void){ float x = 18.0; cout<< x << endl; //displays 18 cout.setf(ios::showpoint); cout<< x << endl; //displays 18.0000 cout.setf(ios::scientific); cout<< x << endl; //displays 1.800000e+001 cout.unsetf(ios::showpoint); cout.unsetf(ios::scientific); cout<<x<<endl; //displays 18getch();return 0; }

Page 14: Lec 47.48 - stream-files

ios Formatting Flagsios Formatting Flags

Since they are the members of the ios Since they are the members of the ios class, they must follow the name ios class, they must follow the name ios and the scope resolution operator;and the scope resolution operator;e.g., e.g., ios::showpointios::showpoint

All the flags must be set using the setf() All the flags must be set using the setf() and usetf() ios member functions;and usetf() ios member functions;e.g., e.g., cout.setf(ios::showpoint)cout.setf(ios::showpoint) cout.unsetf(ios::showpoint)cout.unsetf(ios::showpoint)

Page 15: Lec 47.48 - stream-files

ios Formatting Flagsios Formatting Flags

Many formatting flags can be set using Many formatting flags can be set using manipulatorsmanipulators

Manipulators are formatting instructions Manipulators are formatting instructions inserted directly into a stream; e.g., inserted directly into a stream; e.g., endlendl, , octoct, , setw()setw() etc. etc.

Manipulators come in two flavors:Manipulators come in two flavors:1)1) No-argument ios manipulatorsNo-argument ios manipulators2)2) ios manipulators with argumentsios manipulators with arguments

Page 16: Lec 47.48 - stream-files

No-argument ios ManipulatorsNo-argument ios Manipulators

Page 17: Lec 47.48 - stream-files

ios Manipulators with Argumentsios Manipulators with Arguments

Page 18: Lec 47.48 - stream-files

#include <iostream>#include <iomanip>#include <conio.h>using namespace std;int main(void){ int var = 11; cout << setw(8) << 22 << "\n"; cout << setw(8) << 4444 << "\n"; cout << setw(8) << 666666 << endl;

cout<< var <<“in hexadecimal is ” << hex <<var; cout<< setpercision(5) <<20.99055;getch();return 0; }

Page 19: Lec 47.48 - stream-files

istream Classistream Class

The The istreamistream class is derived from class is derived from iosios class and performs input specific class and performs input specific activities.activities.

Page 20: Lec 47.48 - stream-files
Page 21: Lec 47.48 - stream-files

istream Classistream Class

cin.get():cin.get(): inputs a character from inputs a character from stream (even white spaces) and returns stream (even white spaces) and returns itit

cin.get( c ):cin.get( c ): inputs a character from inputs a character from stream and stores it in stream and stores it in cc

Page 22: Lec 47.48 - stream-files

istream Classistream Class

cin.get(array, size):cin.get(array, size): Accepts 3 arguments: array of characters, the size limit, and Accepts 3 arguments: array of characters, the size limit, and

a delimiter ( default of a delimiter ( default of ‘\n’‘\n’).). Uses the array as a bufferUses the array as a buffer When the delimiter is encountered, it remains in the input When the delimiter is encountered, it remains in the input

stream stream Null character is inserted in the arrayNull character is inserted in the array Unless delimiter flushed from stream, it will stay thereUnless delimiter flushed from stream, it will stay there

cin.getline(array, size)cin.getline(array, size) Operates like Operates like cin.get(buffer, size)cin.get(buffer, size) but it discards the but it discards the

delimiter from the stream and does not store it in arraydelimiter from the stream and does not store it in array Null character inserted into arrayNull character inserted into array

Page 23: Lec 47.48 - stream-files

#include <iostream>#include <conio.h>using namespace std;

int main(){

const int SIZE = 10;char buffer[ SIZE ];

cout << "Enter a sentence:\n";cin.getline( buffer, SIZE );

cout << "\nThe sentence entered is:\n" << buffer << endl;

getch();return 0; }

Page 24: Lec 47.48 - stream-files

ostream Classostream Class

The The ostreamostream class is derived from class is derived from iosios class and handles output or insertion class and handles output or insertion activities.activities.

Page 25: Lec 47.48 - stream-files

ostream Classostream Class

Page 26: Lec 47.48 - stream-files

Stream ErrorsStream Errors Following statements are well-known to Following statements are well-known to

us:us:

cout<<“Good afternoon”cout<<“Good afternoon”OrOr

cin >> varcin >> varWhat if the user enters “five” instead of What if the user enters “five” instead of

“5” for integer variable “var” ?“5” for integer variable “var” ?

Page 27: Lec 47.48 - stream-files

Stream ErrorsStream Errors Following statements are well-known to Following statements are well-known to

us:us:

cout<<“Good afternoon”cout<<“Good afternoon”OrOr

cin >> varcin >> varWhat if the user enters “five” instead of “5” What if the user enters “five” instead of “5”

for integer variable “var” ?for integer variable “var” ?

The compiler will through an error The compiler will through an error message!message!

Page 28: Lec 47.48 - stream-files

Errors-Status BitsErrors-Status Bits The stream error status flags report The stream error status flags report

errors that occur in an input or output errors that occur in an input or output operation.operation.

Page 29: Lec 47.48 - stream-files

Errors-Status BitsErrors-Status Bits

Page 30: Lec 47.48 - stream-files

int i;

while(true) // cycle until input OK { cout << "\nEnter an integer: "; cin >> i; if( cin.good() ) // if no errors { cin.ignore(10, '\n'); // remove newline break; // exit loop } cin.clear(); // clear the error bits cout << "Incorrect input";

cin.ignore(10, '\n'); // remove newline }cout << "integer is " << i; // error-free integer