chapter 9 - sushant's technical articles · pdf fileoutput stream: the output stream is...

29
www.sahajsolns.com Chapter 9 Chapter 9

Upload: vuanh

Post on 13-Mar-2018

229 views

Category:

Documents


6 download

TRANSCRIPT

www.sahajsolns.com

Chapter 9Chapter 9

www.sahajsolns.com

Session Objectives� Stream Class

� Stream Class Hierarchy

� String I/O

Character I/O� Character I/O

� Object I/O

� File Pointers and their manipulations

� Error handling in Files

� Command Line arguments

OOPS WITH C++ Sahaj Computer Solutions 2

www.sahajsolns.com

Introduction� A stream is a general name given to a flow of data.

� There are two types of streams

� Input stream : The input stream is used to read data from a disk file .a disk file .

� Output stream: The output stream is used to write data into the file.

OOPS WITH C++ Sahaj Computer Solutions 3

Disk File Program

Input stream

Output Stream

www.sahajsolns.com

The Stream Class Hierarchy� The stream classes are arranged in a rather complex

hierarchy.

� The extraction operator >> is a member of the istreamclass, and the insertion operator << is a member of the class, and the insertion operator << is a member of the ostream class. Both of these classes are derived from the ios class.

� The cout object, representing the standard output stream, which is usually directed to the video display.

� Similarly cin is an object of the istream_withassignclass, which is derived from istream and is the standard input stream.

OOPS WITH C++ Sahaj Computer Solutions 4

www.sahajsolns.com

The Stream Class Hierarchy� The classes used for input and output to the video

display and keyboard are declared in the header file IOSTREAM.

� The classes used specifically for disk file I/O are � The classes used specifically for disk file I/O are declared in the file FSTREAM.

� The istream and ostream classes are derived from iosand are dedicated to input and output, respectively.

� The istream class contains such functions as get(), getline(), read(), and the overloaded extraction (>>) operators, while ostream contains put() and write(), and the overloaded insertion (<<) operators.

OOPS WITH C++ Sahaj Computer Solutions 5

www.sahajsolns.com

The Stream Class Hierarchy� The iostream class is derived from both istream and

ostream by multiple inheritance.

� Classes derived from it can be used with devices, such as disk files, that may be opened for both input and as disk files, that may be opened for both input and output at the same time.

� Figure below shows the stream class hierarchy

OOPS WITH C++ Sahaj Computer Solutions 6

www.sahajsolns.com

The Stream Class Hierarchy

OOPS WITH C++ Sahaj Computer Solutions 7

www.sahajsolns.com

The istream class� The istream class, which is derived from ios, performs

input-specific activities, or extraction.

� Table below lists the functions you’ll most commonly use use

OOPS WITH C++ Sahaj Computer Solutions 8

Function Purpose

>> Formatted extraction for all basic (and overloaded) types.

get(ch); Extract one character into ch.

get(str) Extract characters into array str, until ‘\n’.fromthe istream class.

get(str, MAX) Extract up to MAX characters into array.

www.sahajsolns.com

The ostream Class� The ostream class handles output or insertion

activities.

� Table below shows the most commonly used member functions of this class.functions of this class.

OOPS WITH C++ Sahaj Computer Solutions 9

Function Purpose

<< Formatted insertion for all basic (and overloaded) types.

put(ch) Insert character ch into stream.

write(str, SIZE) Insert SIZE characters from array str into file.

flush() Flush buffer contents and insert newline.

www.sahajsolns.com

Character I/O� The put() and get() functions, which are members of

ostream and istream, respectively, can be used to output and input single characters.

OOPS WITH C++ Sahaj Computer Solutions 10

www.sahajsolns.com

Writing Character data to a file

// file output with characters#include <fstream.h> //for file functions#include <iostream.h>#include <string.h>int main()

OOPS WITH C++ Sahaj Computer Solutions 11

int main(){string str = “Time is a great teacher, but unfortunately it kills all its pupils. Berlioz”;ofstream outfile(“TEST.TXT”); //create file for outputfor(int j=0; j<strlen (str); j++) //for each character,outfile.put( str[j] ); //write it to filecout << “File written\n”;return 0;}

www.sahajsolns.com

Reading character data from a file// file input with characters#include <fstream.h> //for file functions#include <iostream.h>int main(){char ch; //character to read

OOPS WITH C++ Sahaj Computer Solutions 12

char ch; //character to readifstream infile(“TEST.TXT”); //create file for inputwhile( infile ) //read until EOF or error{infile.get(ch); //read charactercout << ch; //display it}cout << endl;return 0;}

www.sahajsolns.com

Object I/O� Since C++ is an object-oriented language, it’s

reasonable to wonder how objects can be written to and read from disk.

� Writing an Object to Disk� Writing an Object to Disk

� When writing an object, we generally want to use binary mode.

� This writes the same bit configuration to disk that was stored in memory, and ensures that numerical data contained in objects is handled properly.

OOPS WITH C++ Sahaj Computer Solutions 13

www.sahajsolns.com

Writing an Object to Disk// saves person object to disk#include <fstream.h> //for file streams#include <iostream.h>////////////////////////////////////////class person //class of persons{

///////////////////////////////////////////int main(){person pers; //create a person

OOPS WITH C++ Sahaj Computer Solutions 14

{protected:char name[80]; //person’s nameshort age; //person’s agepublic:void getData() //get person’s data{cout << “Enter name: “; cin >> name;cout << “Enter age: “; cin >> age;}};

person pers; //create a personpers.getData(); //get data for person//create ofstream objectofstream outfile(“PERSON.DAT”);//write to itoutfile.write((char*)(&pers), sizeof(pers));return 0;}

www.sahajsolns.com

Reading an Object from Disk// reads person object from disk#include <fstream.h> //for file streams#include <iostream.h>/////////////////////////////////////////class person //class of persons{

//////////////////////////////////////////int main(){

OOPS WITH C++ Sahaj Computer Solutions 15

{protected:char name[80]; //person’s nameshort age; //person’s agepublic:void showData() //display person’s data{cout << “Name: “ << name << endl;cout << “Age: “ << age << endl;}};

{person pers; //create person variableifstream infile(“PERSON.DAT”); //create stream//read streaminfile.read((char *)&pers, sizeof(pers) );pers.showData(); //display personreturn 0;}

www.sahajsolns.com

I/O with Multiple Objects� Our next example opens a file and writes as many

objects as the user wants. Then it reads and displays the entire contents of the file.

// reads and writes several objects to diskvoid getData(){

OOPS WITH C++ Sahaj Computer Solutions 16

// reads and writes several objects to disk#include <fstream> //for file streams#include <iostream>using namespace std;///////////////////////////////////////////class person //class of persons{protected:char name[80]; //person’s nameint age; //person’s agepublic:

{cout << “\n Enter name: “; cin >> name;cout << “ Enter age: “; cin >> age;}void showData(){cout << “\n Name: “ << name;cout << “\n Age: “ << age;}};

www.sahajsolns.com

I/O with Multiple Objectsint main(){char ch;person pers; //create person objectfstream file; //create input/output filefile.open(“GROUP.DAT, ios::app |

while(ch==’y’); //quit on ‘n’file.seekg(0); //reset to start of file//read first personfile.read( (char*)(&pers), sizeof(pers) );while( !file.eof() ) //quit on EOF{

OOPS WITH C++ Sahaj Computer Solutions 17

file.open(“GROUP.DAT, ios::app | ios::out | ios::in |ios::binary);do //data from user to file{cout << “\nEnter person’s data:”;pers.getData(); //get one person’s data//write to filefile.write((char*)(&pers), sizeof(pers) );cout << “Enter another person (y/n)? “;cin >> ch;}

{cout << “\nPerson:”; //display personpers.showData(); //read another personfile.read( reinterpret_cast<char*>(&pers), sizeof(pers) );}cout << endl;return 0;}

www.sahajsolns.com

The fstream class� So far the file objects we have created have been for

either input or output.

� In some cases we want to create a file that can be used for both input and output.for both input and output.

� This requires an object of the fstream class, which is derived from iostream, which is derived from both istream and ostream so it can handle both input and output.

OOPS WITH C++ Sahaj Computer Solutions 18

www.sahajsolns.com

The open() Function� The open() function is used to open multiple files that

use the same stream object.

� Syntax:

file-stream-class stream-object;

� Example:

OOPS WITH C++ Sahaj Computer Solutions 19

file-stream-class stream-object;stream-object. open(“filename”);

ofstream outfile;outfile.open(“DATA1”);………………………….…………………………outfile.close();

www.sahajsolns.com

The Mode Bits� In the open() function we include several new mode

bits.

� The mode bits, defined in ios, specify various aspects of how a stream object will be opened.of how a stream object will be opened.

OOPS WITH C++ Sahaj Computer Solutions 20

Parameters Description

ios::app Append to end-of-file

ios::ate Go to end of file on opening

ios::binary Binary file

ios::in Open file for reading only

ios::nocreate Open fails if the file does not exist

ios::noreplace Opens fails if the file already exists

www.sahajsolns.com

Detecting End-of-File� When we read a file little by little, we will eventually

encounter an end-of-file (EOF) condition.

� The EOF is a signal sent to the program from the operating system when there is no more data to read. operating system when there is no more data to read.

� Example:

while( !infile.eof() ) // until eof encountered

OOPS WITH C++ Sahaj Computer Solutions 21

www.sahajsolns.com

File Pointers� Each file has two associated pointers known as thefile

pointers.

� One of them is called the input pointer(or get pointer ) and the other is called the output pointer( or the put and the other is called the output pointer( or the put pointer)

� We can use these pointers to move through the file while reading or writing.

� The input pointer is used to read the contents of the given file location and the output pointer is used for writing to a given file location and the output pointer is used for writing to a given file location.

OOPS WITH C++ Sahaj Computer Solutions 22

www.sahajsolns.com

Actions on file pointers while

opening a file

H E L L O W O R L D

Input pointer

Open for reading only

OOPS WITH C++ Sahaj Computer Solutions 23

H E L L O W O R L D

Output pointer

Output pointer

Open in append mode (for writing more data)

Open for Writing only

www.sahajsolns.com

Manipulation of File Pointers� The file stream classes support the following

functions to manage such situations:

� Seekg(): moves get pointer(input) to a specified location

� Seekp(): Moves put pointer (outout) to a specified � Seekp(): Moves put pointer (outout) to a specified location.

� Tellg(): Gives the current position of the get pointer.

� Tellp():Gives the current position of the put pointer.

OOPS WITH C++ Sahaj Computer Solutions 24

www.sahajsolns.com

Error Handling During File

Operations� The class ios supports several member functions that

can be used to read the status recorded in a file stream.

� The list of functions are as follows:

� eof(): Returns true(non-zero) if end-of-file is � eof(): Returns true(non-zero) if end-of-file is encountered while reading. Otherwise returns false(zero)

� fail(): Returns true(non-zero) when an input or output operation has failed.

OOPS WITH C++ Sahaj Computer Solutions 25

www.sahajsolns.com

Error Handling During File

Operations� Bad(): Returns true if an invalid operation is attempted

or any unrecoverable error has occurred. However if it is false, it may be possible to recover from any other error reported, and continue operation.reported, and continue operation.

� Good() return true if no error has occurred. This means, all the above functions are false. For instance, if file-good() is true, all is well with the stream file and we can proceed to perform I/O operations. When it returns false, no further operations can be carried out.

OOPS WITH C++ Sahaj Computer Solutions 26

www.sahajsolns.com

Command Line Arguments� Like C, C++ too supports a feature that facilitates the

supply of arguments to the main() function. These arguments are supplied at the time of invoking the program. program.

� Example:

c> exam data results

� Here exam is the name of the file containing the program.

� Data and results are two arguments passed from the command line.

OOPS WITH C++ Sahaj Computer Solutions 27

www.sahajsolns.com

Command Line Arguments� The command line arguments are typed by the user and are

delimited by a space.� The first argument is always the file name and contains the

program to be executed.� The main() function which we have been using up to now � The main() function which we have been using up to now

without arguments can take two arguments as shown main(int argc, char* argv[])

� The first argument argc(also known as argument counter) represents the number of arguments in the command line.

� The second argument argv(also known as argument vector) is an array of a char type pointer that points to the command line arguments.

OOPS WITH C++ Sahaj Computer Solutions 28

www.sahajsolns.com

Command Line Arguments� The size of argument array will be equal to the value

of argc. For example:

C>exam data result

argv[0]�examargv[0]�exam

argv[1]�data

argv[2]�result

OOPS WITH C++ Sahaj Computer Solutions 29