E Balagurusamy: File I/O With Streams
E Balagurusamy: File I/O With Streams
this concept.
Note: Dear Readers the given data has been taken from various books and therefore organised and
written in short para's as notes. It can be wrong at places so dont just read and learn. The data is for
basic concepts. While using this resource, have a book of c++ with you also. Recommended Book: E
BALAGURUSAMY
The data is stored in these devices using the concept of files. A file is a collection of related data stored
in a particular area on the disk.
Programs can be designed to perform the read and write operations on these files.
A program typically involves either or both of the following kinds of data communication:
Data transfer between the console unit and the program.
Data transfer between the program and a disk file.
The input/output system of C++ handles file operations which are very much similar to the console input
and output operations.
It uses file streams as an interface between the programs and the files.
The stream that supplies data to the program is known as input stream and the one that receives data
from the program is known as output stream.
In other words, the input stream extracts or reads data from the file and the output stream inserts or
writes data to the file.
These classes, designed to manage the disk files, are declared in fstream.h and therefore we must
include this file in any program that uses files.
Details of some useful classes :
filebuf
Its purpose is to set the file buffer to read and write. Contains openprot constant used in the open() of
the filestream classes. Also contains close() and open() as member functions.
fstreambase
Provides operations common to the file streams. Serves as a base for fstream, ifstream and ofstream
classes. Contains open() and close() functions.
ifstream
Provides input operations. Contains open() with default input mode. Inherits the functions get(),
getline(), read(), seekg() and tellg() functions from istream.
ofstream
Provides output operations. Contains open() with default output mode. Inherits put(), seekp(), tellp(),
and write() functions from ostream.
fstream
Provides support for simultaneous input and output operations. Contains open() with default input
mode. Inherits all the functions from istream and ostream classes through iostream.
The ifstream, ofstream and fstream classes are declared in the file fstream.h
The istream and ostream classes are also included in the fstream.h file.
Opening and closing a file :
For opening a file, we must first create a file stream and than link it to the filename.
A filestream can be defined using the classes ifstream, ofstream, and fstream that are contained in the
header file fstream.h
Using the member function open() of the class. This method is used when we want to manage multiple
files using one stream.
Using Constructor
Create a file stream object to manage the stream using the appropriate class. That is, the class ofstream
is used to create the output stream and the class ifstream to create the input stream.
ofstream outfile(“sample.txt”);
The above statement creates an object outfile of class ofstream that manages the output stream. This
statement also opens the file sample.txt and attaches it to the output stream for writing.
Similarly, the statement declared in as an ifstream object and attaches to the file “sample.txt” for
reading.
ifstream infile(“sample.txt”);
# include
void main()
{
ofstream outfile(“sample.txt”); // create file for output
char ch = ‘a’;
int i = 12;
float f = 4356.15;
char arr[ ] = “hello”;
outfile << ch << endl <<< endl << f << endl << arr; //send the data to file
outfile.close();
ifstream infile(“sample.txt”);
infile >> ch >> i >> f >> arr; // read data from file
#include
#include
void main()
{
char str[]=“C++ is superset of C. It is an object-oriented /
programming language.”;
The binary input and output functions read() and write() are designed to do exactly this job.
The write() function is used to write the object of a class into the specified file and read() function is used
to read the object of the class from the file.
The address of the object must be cast to the type pointer to char.
One important point to remember is that only data members are written to the disk file and the member
functions are not.
#include
class Person
{
private:
char name[40];
int age;
public:
void getData()
{
cout << “\n Enter name:”; cin >> name;
cout << “\n Enter age:”; cin >> age;
}
} ; // End of the class definition
void main()
{
Person per ; // Define an object of Person class
In the open() function we include several mode bits to specify certain aspects of the file object.
app -> To preserve whatever was in the file before. Whatever we write to the file will be appended to the
existing contents.
We use in and out because we want to perform both input and output on the file.
eof() is a member function of ios class. It returns a nonzero value if EOF is encountered and a zero
otherwise.
Parameters of open() function
Parameter Meaning
ios::app Append to end of the file
ios::ate Go to end of the file on opening
ios::in Open file for reading only
ios::nocreate Open fails if the file does not exist
ios::noreplace Open fails if the file already exists
ios::out Open file for writing only
ios::trunc Delete contents of the file if it exists
Each file has two associated pointers known as the file pointers.
We can use these pointers to move through the files while reading or writing.
The input pointer is used for reading the contents of a given file location and the output pointer is used
for writing to a given file location.
infile.seekg(10);
Moves the file pointer to the byte number 10.
Thus, the pointer will be pointing to the 11th byte in the file.
Specifying the offset :
The seek functions seekg() and seekp() can also be used with two arguments as follows:
seekg(offset, refposition);
seekp(offset, refposition);
The parameter offset represents the number of bytes the file pointer to be moved from the location
specified by the parameter refposition.
The refposition takes one of the following these constant defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file.
This program counts the number of objects already written into the file “Person.txt”. Then is reads the
second object and displays the values of its data members.
class person
{
private:
char name[40];
int age;
public:
void showData()
{
cout << “\n Name = “ << name;
cout << “\n Age = “ << age;
}
};
void main()
{
person pers; // create person object
ifstream infile; // create input file
infile.open(“Person.txt”); // open the file
infile.seekg(0, ios::end); // go to end from 0 byte
int endposition = infile.tellg(); // find where we are
int n = endposition/sizeof(person); // number of persons
cout << “\n There are “ << n << “ persons in file: “;
cout << “\n Enter person number: “;
cin >> n;
int position = (n-1) * sizeof(person); // number times size
infile.seekg(position);
infile.read( (char*)&pers, sizeof(pers) );
pers.showData(); // display the person
}