098ca session7 c++

76
1 Course Name- B Sc Subject Name - C++ Semester - II Neetu Gupta

Upload: mukund-trivedi

Post on 02-Nov-2014

708 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: 098ca session7 c++

1

Course Name- B Sc

Subject Name - C++

Semester - II

Neetu Gupta

Page 2: 098ca session7 c++

Contents

• streams• IOS• IOStream library• Class hierarchy• Organisation• Streambuf• Ostream• istream

Page 3: 098ca session7 c++

Contents

• File handling

• ofstream, ifstream, fstream

Page 4: 098ca session7 c++

IOstream Library

• This is usually called as Standard Input / Output Streams Library

• The iostream library is an object-oriented library that provides input and output functionality using streams.

Page 5: 098ca session7 c++

What is a stream?• A stream is an abstraction that represents a device on which input

and output operations are performed.

• A stream can basically be represented as a source or destination of characters of indefinite length.

• Streams are generally associated to a physical source or destination of characters, like a disk file, the keyboard, or the console, so the characters gotten or written to/from our abstraction called stream are physically input/output to the physical device.

• For example, file streams are C++ objects to manipulate and interact with files; Once a file stream is used to open a file, any input or output operation performed on that stream is physically reflected in the file.

Page 6: 098ca session7 c++

• C++ provides a complete set of abstract classes and concrete classes for input/output.

• The classes are divided into groups that few work with files, few on streams, string or characters etc.

• A complete class hierarchy diagram is as

CLASS HIERARCHY DIAGRAM

Page 7: 098ca session7 c++
Page 8: 098ca session7 c++

Organization

• The library and its hierarchy of classes is split in different files:

1. <ios>, <istream>, <ostream>, <streambuf> and <iosfwd> aren't usually included directly in most C++ programs.

– They describe the base classes of the hierarchy and are automatically included by other header files of the library that contain derived classes.

2. <iostream> declares the objects used to communicate through the standard input and output (including cin and cout).

Page 9: 098ca session7 c++

3. <fstream> defines the file stream classes (like the template basic_ifstream or the class ofstream) as well as the internal buffer objects used with these (basic_filebuf).

– These classes are used to manipulate files using streams.

4. <sstream>: The classes defined in this file are used to manipulate string objects as if they were streams.

Page 10: 098ca session7 c++

streambuf

• streambuf is Base buffer class for streams

• streambuf objects are in charge of providing reading and writing functionality to/from certain types of character sequences, such as external files or strings.

• streambuf objects are usually associated with one specific character sequence, from which they read and write data through an internal memory buffer.

Page 11: 098ca session7 c++

• This is an abstract base class, therefore no objects can be directly instantiated from it.

• The standard hierarchy defines two classes derived from this one that can be used to directly instantiate objects: filebuf and stringbuf.

Page 12: 098ca session7 c++

ostream

• It is a output stream.

• The class hierarchy is as :

ios_base ios ostream

ostringstream

ofstream

iostream

Page 13: 098ca session7 c++

• ostream objects are stream objects used to write and format output as sequences of characters.

• Specific members are provided to perform these output operations, which can be divided in two main groups:

1. Formatted output These member functions interpret and format the data to be written as sequences of characters.

These type of operation is performed using member and global functions that overload the insertion operator (operator<<).

Page 14: 098ca session7 c++

2. Unformatted output Most of the other member functions of the ostream class are used to perform unformatted output operations, i.e. output operations that write the data as it is, with no formatting adaptations.

These member functions can write a determined number of characters to the output character sequence (put, write) and manipulate the put pointer (seekp, tellp).

• The standard objects cout, cerr and clog are instantiations of this class.

Page 15: 098ca session7 c++

• ostream class inherits all the internal fields from its parent classes i.e. ios_base and ios:

1. Formatting information • format flags: a set of internal indicators describing how

certain input/output operations shall be interpreted or generated. The state of these indicators can be obtained or modified by calling the members flags, setf and unsetf, or by using manipulators.

• field width: describes the width of the next element to be output. This value can be obtained/modified by calling the member function width or parameterized manipulator setw.

• display precision: describes the decimal precision to be used to output floating-point values. This value can be obtained/modified by calling member precision or parameterized manipulator setprecision.

Page 16: 098ca session7 c++

• fill character: character used to pad a field up to the field width. It can be obtained or modified by calling member function fill or parameterized manipulator setfill.

• locale object: describes the localization properties to be considered when formatting i/o operations. The locale object used can be obtained calling member getloc and modified using member imbue.

2. State information • error state: internal indicator reflecting the integrity and

current error state of the stream. The current object may be obtained by calling rdstate and can be modified by calling clear and setstate. Individual values may be obtained by calling good, eof, fail and bad.

• exception mask: internal exception status indicator. Its value can be retrieved/modified by calling member exceptions.

Page 17: 098ca session7 c++

3. Other – event function stack: stack of pointers to callback

functions that are called when certain events occur. Additional callback functions may be registered to be called when an event occurs, using member function register_callback.

– internal extensible arrays: two internal arrays to store long objects and void pointers. These arrays can be extended by calling member function xalloc, and references to these objects can be retrieved with iword or pword.

– pointer to tied stream: pointer to the stream object which is tied to this stream object. It can be obtained/modified by calling member function tie.

– pointer to stream buffer: pointer to the associated streambuf object. It can be obtained/modified by calling member function rdbuf.

Page 18: 098ca session7 c++

public members - ostream

(constructor) Construct object (constructor member)

(destructor) Destruct object (destructor member)

Formatted output:operator<< - Insert data with format (public member function)

Unformatted output:put - Put character (public member function)write - Write block of data (public member function)

Page 19: 098ca session7 c++

Positioning:tellp -Get position of put pointer (public member function)

seekp- Set position of put pointer (public member function )

Synchronization:flushFlush output stream buffer (public member function)

Page 20: 098ca session7 c++

istream

• It is a input stream class.

• The class hierarchy is as :

ios_base ios istream

istringstream

ifstream

iostream

Page 21: 098ca session7 c++

• istream objects are stream objects used to read and interpret input from sequences of characters.

• Specific members are provided to perform these input operations, which can be divided in two main groups:

1. Formatted input These functions extract data from a sequence of characters that may be interpreted and formatted to a value of a certain type. These type of operation is performed using member and global functions that overload the extraction operator ().

Page 22: 098ca session7 c++

2. Unformatted input Most of the other member functions of the istream class are used to perform unformatted input, i.e. no interpretation is made on the characters got form the input. These member functions can get a determined number of characters from the input character sequence (get, getline, peek, read, readsome), manipulate the get pointer i(ignore, seekg, tellg, unget) or get information of the last unformatted input operation (gcount).

• Additionally, a member function exists to synchronize the stream with the associated external source of characters: sync.

• The standard object cin is an instantiation of this class.

Page 23: 098ca session7 c++

• The class inherits all the internal fields from its parent classes ios_base and ios:

1. Formatting information – format flags: a set of internal indicators describing how certain

input/output operations shall be interpreted or generated. The state of these indicators can be obtained or modified by calling the members flags, setf and unsetf, or by using manipulators.

– field width: describes the width of the next element to be output. This value can be obtained/modified by calling the member function width or parameterized manipulator setw.

– display precision: describes the decimal precision to be used to output floating-point values. This value can be obtained/modified by calling member precision or parameterized manipulator setprecision.

– fill character: character used to pad a field up to the field width. It can be obtained or modified by calling member function fill or parameterized manipulator setfill.

– locale object: describes the localization properties to be considered when formatting i/o operations. The locale object used can be obtained calling member getloc and modified using member imbue.

Page 24: 098ca session7 c++

2. State information • error state: internal indicator reflecting the

integrity and current error state of the stream. The current object may be obtained by calling rdstate and can be modified by calling clear and setstate. Individual values may be obtained by calling good, eof, fail and bad.

• exception mask: internal exception status indicator. Its value can be retrieved/modified by calling member exceptions.

Page 25: 098ca session7 c++

3. Other – event function stack: stack of pointers to callback

functions that are called when certain events occur. Additional callback functions may be registered to be called when an event occurs, using member function register_callback.

– internal extensible arrays: two internal arrays to store long objects and void pointers. These arrays can be extended by calling member function xalloc, and references to these objects can be retrieved with iword or pword.

– pointer to tied stream: pointer to the stream object which is tied to this stream object. It can be obtained/modified by calling member function tie.

– pointer to stream buffer: pointer to the associated streambuf object. It can be obtained/modified by calling member function rdbuf.

Page 26: 098ca session7 c++

public members - istream• (constructor) Construct object (constructor member)

• (destructor) Destruct object (destructor member)

• Formatted input:operator>> Extract formatted data (public member function )

• Positioning:tellg - Get position of the get pointer. (public member function)seekg - Set position of the get pointer (public member function )

• Synchronization:sync - Synchronize input buffer with source of characters (public member function)

Page 27: 098ca session7 c++

• Unformatted input:1. gcount - Get number of characters extracted by last

unformatted input operation (public member function)2. get - Get unformatted data from stream (public member

function )3. Getline - Get line from stream (public member function )4. Ignore - Extract and discard characters (public member

functions)5. Peek - Peek next character (public member function )6. Read - Read block of data (public member function)7. Readsome - Read block of data available in the buffer

(public member function )8. Putback - Put character back (public member function )9. Unget - Decrement get pointer (public member

function )

Page 28: 098ca session7 c++

File Handling

C++ provides the following classes to perform output and input of characters to/from files:

1. ofstream: Stream class to write on files

2. ifstream: Stream class to read from files

3. fstream: Stream class to both read and write from/to files.

Page 29: 098ca session7 c++

• These classes are derived directly or indirectly from the classes istream, and ostream.

• We have already used objects whose types were these classes:

cin is an object of class istreamcout is an object of class ostream

• Therefore, we have already been using classes that are related to our file streams.

• And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files.

Page 30: 098ca session7 c++

Why file handling

• Convenient way to deal large quantities of data.• Store data permanently (until file is deleted).• Avoid typing data into program multiple times.• Share data between programs.

We need to know:how to "connect" file to programhow to tell the program to read datahow to tell the program to write dataerror checking and handling EOF

Page 31: 098ca session7 c++

A sample code

// basic file operations #include <iostream> #include <fstream> using namespace std; int main () {

ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0;

}

Page 32: 098ca session7 c++

• This code creates a file called example.txt

• Inserts a sentence into it in the same way we are used to do with cout,

• But it is using the file stream myfile instead of using the standard output stream i.e. cout.

Page 33: 098ca session7 c++

Step1 – open a file

• The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file.

• An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and

• Any input or output operation performed on this stream object will be applied to the physical file associated to it.

Page 34: 098ca session7 c++

open function

• In order to open a file with a stream object i.e. an object of type ofstream we use its member function open():

open (filename, mode);

Where filename - is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened,

mode - is an optional parameter with a combination of the following flags:

Page 35: 098ca session7 c++

modesios::in Open for input operations.

ios::out Open for output operations.

ios::binary Open in binary mode.

ios::ate Set the initial position at the end of the file.

If this flag is not set to any value, the initial position is the beginning of the file.

ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.

ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

Page 36: 098ca session7 c++

• All these mode flags can be combined using the bitwise operator OR (|).

• For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open():

ofstream myfile;

myfile.open ("example.bin", ios::out | ios::app | ios::binary);

Page 37: 098ca session7 c++

• For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function.

Page 38: 098ca session7 c++

Default open mode

• If we do not specify any mode with the open function, it assumes some default values depending upon the type of stream object you are creating.

• Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:

Page 39: 098ca session7 c++

classdefault mode parameter

ofstream ios::out

ifstream ios::in

fstream ios::in | ios::out

Page 40: 098ca session7 c++

• For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function.

• The default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.

Page 41: 098ca session7 c++

• File streams opened in binary mode perform input and output operations independently of any format considerations.

• Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).

Page 42: 098ca session7 c++

Using constructor to open a file

• Since the first task that is performed on a file stream object is generally to open a file, these three classes include a constructor that automatically calls the open() member function and has the exact same parameters as this member function.

• Therefore, we could also have declared the previous myfile object and conducted the same opening operation in our previous example by using the constructor only, that will create the stream object for file and will open it as well:

Page 43: 098ca session7 c++

 ofstream myfile ("example.bin", ios::out | ios::app |

ios::binary);

• Combining object construction and stream opening in a single statement.

• Both forms to open a file are valid and equivalent.

Page 44: 098ca session7 c++

Error checking for opening a file

• To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments.

• This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:

if (myfile.is_open()) { /* ok, proceed with output */

}

Page 45: 098ca session7 c++

Step 2. Using the file stream object

• After the file stream is opened successfully with desired opening mode, we can use the object to read/write data to the file

• For example, if I need to open a file for output operations and want o write some data to file, we will write a code lines like

Page 46: 098ca session7 c++

……….// create an object of ofstream typeofstream myfile;

// open the stream for file example.txt.// note – no open mode is specified so // default will be used i.e. ios::out here // as it is an objetc of ofstream classmyfile.open ("example.txt");

// use the myfile object to write to file.// note – the use of << to write to file, in the same // way as with cout.myfile << "Writing this to a file.\n"; ……………

Page 47: 098ca session7 c++

Step 3 – close a file

• When we are finished with our input and output operations on a file we shall close it so that its resources become available again for some other process/program for further usage of the same file.

• In order to do that we have to call the stream's member function close().

• This member function takes no parameters, and what it does is – to flush the associated buffers and – close the file.

Page 48: 098ca session7 c++

Syntax – close()

• The code will be likemyfile.close();

Where myfile is a stream object already opened with the open member function.

• Once this member function is called, the stream object like myfile here can be used to open another file,

• The file is available again to be opened by other processes.

Page 49: 098ca session7 c++

Text files

• Text file streams are those where we do not include the ios::binary flag in their opening mode.

• These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.

• These are the types of files those are widely used for storing data.

Page 50: 098ca session7 c++

Data output on text files

• Data output operations on text files are performed in the same way we operated with cout.

• We can create an object of type ofstream and use this stream object for any output to the associated file.

• Example to write to file example.txt

Page 51: 098ca session7 c++

// writing on a text file

#include <iostream> #include <fstream> using namespace std; int main () {

ofstream myfile ("example.txt"); if (myfile.is_open()) {

myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close();

} else {

cout << "Unable to open file"; }return 0;

}

Page 52: 098ca session7 c++

• After running the above program, see the contents of file example.txt.

• The contents will be what we write to file in the program as

[file example.txt]

This is a line.

This is another line.

Page 53: 098ca session7 c++

Data input from a text files

• Data input from a file can also be performed in the same way that we did with cin.

• We can create an object of type ofstream and use this stream object for any output to the associated file.

• Example to read from file example.txt

Page 54: 098ca session7 c++

// reading a text file #include <iostream> #include <fstream> #include <string> using namespace std; int main () {

string line; ifstream myfile ("example.txt"); if (myfile.is_open()) {

while ( myfile.good() ) {

getline (myfile,line); cout << line << endl;

} myfile.close();

} else {

cout << "Unable to open file"; }

return 0; }

Page 55: 098ca session7 c++

• This last example reads a text file and prints out its content on the screen.

• Notice how we have used a new member function, called good() that returns true in the case that the stream is ready for input/output operations.

• We have created a while loop that finishes when indeed myfile.good() is no longer true, which will happen either

• if the end of the file has been reached or • if some other error occurred.

Page 56: 098ca session7 c++

Checking status flags

• In addition to good(), which checks whether the stream is ready for input/output operations, other member functions exist to check for specific states of a stream

• All of them return a bool type value.

Page 57: 098ca session7 c++

bad() – Returns true if a reading or writing operation

fails. – For example in the case that we try to write to

a file that is not open for writing or if the device where we try to write has no space left.

fail() – Returns true in the same cases as bad(), but

also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number.

Page 58: 098ca session7 c++

eof() – Returns true if a file open for reading has reached the

end.

good() – It is the most generic state flag: it returns false in the

same cases in which calling any of the previous functions would return true.

In order to reset the state flags checked by any of these member functions we have just seen we can use the member function clear(), which takes no parameters.

Page 59: 098ca session7 c++

get and put stream pointers

• All i/o streams objects have, at least, one internal stream pointer.

• ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation.

• ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written.

Page 60: 098ca session7 c++

• Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream).

• These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions:

• tellg() and tellp()• seekg() and seekp()

Page 61: 098ca session7 c++

tellg()

• Get position of the get pointer.

• Returns the absolute position of the get pointer.

• The get pointer determines the next location in the input sequence to be read by the next input operation.

Page 62: 098ca session7 c++

streampos tellg ( );

• Parameters :none

• Return ValueAn integral value of type streampos with the number of characters between the beginning of the input sequence and the current position.

• Failure is indicated by returning a value of -1.

Example: In this example, tellg is used to get the position in the stream after it has been moved with seekg to the end of the stream, therefore determining the size of the file.

Page 63: 098ca session7 c++

// read a file into memory #include <iostream> #include <fstream> using namespace std; int main () {

int length; char * buffer; ifstream is;is.open ("test.txt", ios::binary ); // get length of file: is.seekg (0, ios::end); length = is.tellg(); is.seekg (0, ios::beg);

// allocate memory: buffer = new char [length]; // read data as a block: is.read (buffer,length); is.close(); cout.write (buffer,length); return 0;

}

Page 64: 098ca session7 c++

tellp

• Get position of put pointer• Returns the absolute position of the put

pointer.

The put pointer determines the location in the output sequence where the next output operation is going to take place.

Page 65: 098ca session7 c++

• Parameters: none • Return Value

An integral value of type streampos with the number of characters between the beginning of the output sequence and the current position.

• Failure is indicated by returning a value of -1.

• Example: In this example, tellp is used to get the position of the put pointer after the writing operation. The pointer is then moved back 7 characters to modify the file at that position, so the final content of the file shall be:

This is a sample

Page 66: 098ca session7 c++

// position of put pointer #include <fstream> using namespace std; int main () {

long pos; ofstream outfile; outfile.open ("test.txt"); outfile.write ("This is an apple",16); pos=outfile.tellp(); outfile.seekp (pos-7); outfile.write (" sam",4); outfile.close(); return 0;

}

Page 67: 098ca session7 c++

seekg()

• Set position of the get pointer

• Sets the position of the get pointer.

• The get pointer determines the next location to be read in the source associated to the stream.

istream& seekg ( streampos pos );

istream& seekg ( streamoff off, ios_base::seekdir dir );

Page 68: 098ca session7 c++

• Parameters

pos: The new position in the stream buffer. This parameter is an integral value of type streampos.

Off: Integral value of type streamoff representing the offset to be applied relative to an absolute position specified in the dir parameter.

Dir: Seeking direction. It is an object of type ios_base::seekdir that specifies an absolute position from where the offset parameter off is applied. It can take any of the following member constant values:

value offset is relative to...

ios_base::beg beginning of the stream buffer

ios_base::cur current position in the stream buffer

ios_base::end end of the stream buffer

Page 69: 098ca session7 c++

• Return Value : The function returns *this.• Errors are signaled by modifying the internal

state flags:

flag error

eofbit -

failbitThe parameter(s) describe a position that

could not be reached.

badbit An error other than the above happened.

Additionally, in any of these cases, if the appropriate flag has been set with member function ios::exceptions, an exception of type ios_base::failure is thrown.

Page 70: 098ca session7 c++

// load a file into memory - // In this example seekg is used to move the get pointer to the end of the file, and then back to the

beginning.

#include <iostream> #include <fstream> using namespace std; int main () {

int length; char * buffer; ifstream is; is.open ("test.txt", ios::binary ); // get length of file: is.seekg (0, ios::end); length = is.tellg(); is.seekg (0, ios::beg); // allocate memory: buffer = new char [length]; // read data as a block: is.read (buffer,length); is.close(); cout.write (buffer,length); delete[] buffer; return 0;

}

Page 71: 098ca session7 c++

seekp

ostream& seekp ( streampos pos );

ostream& seekp ( streamoff off, ios_base::seekdir dir );

• Set position of put pointer

• Sets the position of the put pointer.

• The put pointer determines the location in the output sequence where the next output operation is going to take place.

Page 72: 098ca session7 c++

• Parameterspos: The new position in the stream buffer. This parameter is

an integral value of type streampos.

off: Integral value of type streamoff representing the offset to be applied relative to an absolute position specified in the dir parameter.

dir: Seeking direction. It is an object of type ios_base::seekdir that specifies an absolute

value offset is relative to...

ios_base::beg beginning of the stream buffer

ios_base::cur current position in the stream buffer

ios_base::end end of the stream buffer

 

Page 73: 098ca session7 c++

• Return ValueThe function returns *this.• Errors are signaled by modifying the internal state

flags:

flag error

eofbit -

failbit

The parameter(s) describe a position that could not be reached.

badbitAn error other than the above

happened.

Page 74: 098ca session7 c++

// position of put pointer #include <fstream> using namespace std; int main () {

long pos; ofstream outfile; outfile.open ("test.txt"); outfile.write ("This is an apple",16); pos=outfile.tellp(); outfile.seekp (pos-7); outfile.write (" sam",4); outfile.close(); return 0;

}

Page 75: 098ca session7 c++

• In this previous example,

seekp is used to move the put pointer back to a position 7 characters before the end of the first output operation.

The final content of the file shall be:This is a sample

Page 76: 098ca session7 c++

Thank You

76