Stream Classes(Class hierarchy)
• A stream is a name given to flow of data. In C++ stream is represented by an object of a particular class e.g. cin and cout are input and output stream objects.• There are no any formatting characters in stream like %d, %c etc in C which removes major source of errors.
• Due to overloading operators and functions, we can make them work with our own classes.
Class Hierarchy
• filebuf: The class filebuf sets the file buffer to read and write.• ios: ios class is parent of all stream classes and contains the majority of C++ stream features.
• istream class: Derived from ios and perform input specific activities.
• ostream class: derived from ios class and perform output specific activities.
• iostream class: Derived from both istream and ostream classes, it can perform both input and output activities and used to derive iostream_withassign class.
• _withassign classes: There are three _withassign classes.
– istream_withassign
– ostream_withassign
– iostream_withasssign
• These classes are much like those of their parent but include the overloaded assignment operators.
• streambuf: sets stream buffer i.e. an area in memory to hold the objects actual data. Each object of a class associated with the streambuf object so if we copy the stream object it cause the confusion that we are also copying streambuf object. So _withassign classes can be used if we have to copy otherwise not.
• fstreambase: Provides operations common to file streams. Serves as a base for fstream, ifstream and ofstream and contains open() and close() functions.
• ifstream: Contains input operations in file. Contains open() with default input mode, inherits get(), getline() read(), seekg(), tellg() from istream.
• ofstream: Provides output operation in file. Contains open() with default output mode, inherits put(). Seekp(), tellp() and write() from ostream.
• fstream: Provides support for simultaneous input and output operations. Contains open() with default input mode: Inherits all the functions of istream and ostream through iostream.
File I/O
File I/O with stream classes:
• In C++,file handling is done by using C++ streams.• The classes in c++ for file I/O are ifstream for input files,ofstream for output files, and fstream for file used for both input and output operation. These classes are derived classes from istream,ostream,and iostream respectively and also from fstreambase.
-The header file for ifstream,ofstream and fstream classes is
-To create and write disk file we use ofstream class and create object of it.
e.g. ofstream outf;
• The creation and opening file for write operation is done either using its constructor or using open() member function which had already been defined in ofstream class.
• Creating and opening file for write operation is as:
ofstream outf(“myfile.txt”);
//using constructor of ofstream class.
Or
ofstream outf;
outf.open(“myfile.txt”);
// using open() member function.
Writing text into file
• We use the object of ofstream to write text to file created as:– outf<<”This is the demonstration of file operation\n”;
– outf<<”You can write your text\n”;
– outf<<”The text are written to the disk files\n”;
An example for writing to disk file.
Reading data from file
• To read data from file , we use an object of ifstream class and file is opened for reading using constructor of ifstream class or open() member function as;ifstream fin("test.txt"); //constructor
or
ifstream fin;
fin.open("test.txt"); // member function open();
• Reading data is done as:
• fin>>ch>>i>>f>>str; which is similar as reading data from keyboard by cin object.
• String with embedded blanks:
-Require delimiter line \n for each string with embedded blank and read/write operation is easy.
Reading text from file
• To read text from file we use ifstream class and file is opened for read operation using constructor or open() member function.An example: Reading text from file
Character I/O in file[ get() and put() function]
• put() and get() functions are members of ostream and istream classes.• These functions are inherited to ofstream and ifstream objects in class heirarchy.
• put() is used to write a single character in file.
• Similarly get() function is used for reading a character from file.
Example: writhing character
Example: writhing character
Writing and reading of user Input
• We can also write user-input (values of variables in a program input from keyboard) by ofstream object.• Also can read those values in user variable from file by using objects of ifstream respectively same as done above .
• Look at the simple program example in next.
Opening file in different mode
• In above example we have used the ofstream and ifstream constructors or open() member function using only one argument i.e.filename e.g. “test.txt” etc.
• However this can be done by using two
argument : one is filename and another is filemode.
The Syntax for using file mode is:
Stream-object.open(“filename”,filemode);
The File Mode Parameter
• The second argument filemode is the parameter which is used for what purpose the file is opened.• If we haven’t used any filemode argument and only filename with open() function, the default mode is as:
• ios::in for ifstream functions means open for reading only.
• i.e. fin.open(“test.txt”); is equivalent to fin.open(“test”,ios::in); as default
• ios::out for ofstream functions means open for writing only. fout.open(“test”); is same as fout.open(“test”,ios::out); as default.
NOTE:
Class fstream inherits all features of ifstream and ofstream so we can use fstream object for both input/output operation in file. When fstream class is used , we should mention the second parameter
The File Mode Parameter
• The file mode parameter can take one or more such predefined constants in ios class. The following are such file mode parameters.• Opening file in ios::out mode also opens in the ios::trunc mode default
• ios::app and ios::ate takes to the end-of-file when opening but only difference is that ios::app allows to add data only end-of-file but ios::ate allows us to add or modify data at anywhere in the file. In both case file is created if it does not exists.
• Creating a stream ofstream default implies output(write) mode and ifstream implies input(read), but fstream stream does not provide default parameter so we must provide the mode parameter with fstream.
• The mode can combine two or more parameters using bitwise OR operator (|)
e.g. fout.open(“test”,ios::app|ios::out);
File Pointers
• The file management system associates two types of pointers with each file.• get pointer (input pointer)
• put pointer (output pointer)
• These pointers facilitate the movement across the file while reading and writing.
• The get pointer specifies a location from where current read operation initiated.
• The put pointer specifies a location from where current write operation initiated.
• The file pointer is set to a suitable location initially depending upon the mode which it is opened.
• Read-only Mode: When a file is opened in read-only mode, the input (get) pointer is initialized to the beginning of the file.
• Write-only: mode: In this mode, existing contents are deleted if file exists and put pointer is set to beginning of the file.
• Append mode: In this mode, existing contents are unchanged and put pointer is set to the end of file so writing can be done from end of file.
I/O Pointer in different Mode
Functions manipulating file pointers
• C++ I/O system supports 4 functions for setting a file to any desired position inside the file. The functions are • These all four functions are available in fstream class by inheritance. The two seek() functions have following prototypes.istream & seekg (long offset, seek_dir origin =ios::beg);
ostream & seekp (long offset, seek_dir origin=ios::beg);
• Both functions set file ptr to a certain offset relative to specified origin. The origin is relative point for offset measurement. The default value for origin is ios::beg. (seek_dir) an enumeration declaration given in ios class as
Seek function offset position
Similarly:ofstream outfile;
outfile.seekp(20,ios::beg);
// out file. seek p (20);
moves file put pointer to 20th byte and if write operation is initiated, start writing from 21st item.
Example
Consider below example:ofsteam outfile("student",ios::app);
int size=outfile.tellp();
• Returns the size of file in byte to variable size since ios::app takes file put ptr at end of file. The function tellp() returns the takes file put ptr at end of file. The function tellp() returns the current position of put ptr.
Equivalently:
ifstream infile("student");
infile.seekg(0,ios::end);
int size=infile.tellg() ;
• This returns the current file pointer position which is at end of file so we get he size of fife "student".
Pointer Call with seek()
Some of pointer offset calls and their actions:Assume ofstream object: ofstream fout;
File I/O with fstrem class
• fstream class supports simultaneous input/output operations using same object.• It inherits function from istream and ostream class through iostream.
Character I/O in file
The put () and get () function:
• The function get() is a member function of the file stream class fstream, and used to read a single character from file.• The function put() is member function of fstream class and used to write a single character into file.
The write () and read () function
• The write() function is a member of stream class fstream and used to write data in file as binary format.• The read() function is used to read data (binary form) from a file.
• The data representation in binary format in file is same as in system. The no of byte required to store data in text form is proportional to its magnitude but in binary form, the size is fixed.
Size of data in file
read() and write() function
• The prototype for read () & write () functions are as:.infile.read((char*)&variable, sizeof(variable));
outfile.write((char*)&variable, sizeof(variable));
• The first parameter is a pointer to a memory location at which the data is to be retrieved [read()] or to be written [write()] function.
• The second parameter indicates the number of bytes to be transferred.
Example :writing variable in to files
Object I/O in file
• C++ is Object-oriented language so we need objects to be written in file and read from file .• Following examples show the I/O operations .
• Writing object to disk file:
– Generally binary mode is used which writes object in disk in bit configurations
– Follow the example in next.