CHAPTER NO 8.
FILE STREAM MANAGEMENT
INTRODUCTION,
HIERARCHY OF FILE STREAM CLASSES,
FILE OPERATIONS,
VARIOUS FILE MODES,
FILE POINTERS & THEIR MANIPULATION,
COMMAND LINE ARGUMENTS
Introduction:
File : The information / data stored under a specific name on a storage device, is called a file.
Stream : It refers to a sequence of bytes.
Text file : It is a file that stores information in ASCII characters. In text files, each line of text is
terminated with a special character known as EOL (End of Line) character or delimiter
character. When this EOL character is read or written, certain internal translations take
place.
Binary file : It is a file that contains information in the same format as it is held in memory. In binary
files, no delimiters are used for a line and no translations occur here.
Classes for file stream operation
Ifstream : Stream class to read from files
Fstream : Stream class to both read and write from/to files.
Ofstream : Stream class to write on files.
These classes are derived directly or indirectly from the classes istream and ostream.
We have already used objects whose types were these classes:
o cin is an object of class istream and
o cout is an object of class ostream.
We can use our file streams the same way we are already used to use cin and cout.
The only difference is that we have to associate these streams with physical files.
Example:
#include <iostream.h>
#include <fstream.h>
int main ()
{
ofstream myfile;
myfile.open ("galaxy.txt");
myfile << "Galaxy Computer Education, Chopda\n";
myfile.close();
return 0;
}
Opening a file
Subject: OOP (C++) Print Date: 16-10-2018 Page 1 of 6
Opening file using constructor
ofstream fout(“results.txt”); //output only
ifstream fin(“data.txt”); //input only
Opening file using open()
ofstream ofile;
ofile.open(“data1.txt”);
ifstream ifile;
ifile.open(“data2.txt”);
File Mode parameter and their meaning
ios::app : Append to end of file (i.e. All output operations are performed at the end of the file,
Appending the content to the current content of the file.)
ios::ate : go to end of file on opening. (i.e. Set the initial position at the end of the file.
If this flag is not set, the initial position is the beginning of the file.)
ios::binary : File is open in binary mode
ios::in : Open file for reading only. (File is open for Reading Operation only)
ios::out : Open file for writing only. (File is open for Writing Operation only)
ios::trunc : If the file is opened for output operations and it already existed,
its previous content is deleted and replaced by the new one.
Default Mode of object if we open the file without mode (second parameter)
ios::in is default mode for ifstream object
(ios::out is default mode for ofstream object
(ios::in | ios::out is default mode for fstream object
Open the file with cobination of more than one flag.
All these flags can be combined using the bitwise operator OR (|).
For example, : If we want to open the file “test.bin” in binary mode to add data we could do it by the
following call to member function open():
fstream file;
file.open ("test.bin", ios::out | ios::app | ios::binary);
Note : All File stream classes include a constructor that automatically calls the open member function and has
the exact same parameters as this member.
So we can also declared the previous file object for opening operation in above example as follow:
ofstream file ("test.bin", ios::out | ios::app | ios::binary);
To check if a file stream was successful opening a file,
We can check it by calling to member is_open.
This member function returns a bool value true, when the stream object is connected with an open file,
otherwise it returns false.
Example:
#include <iostream.h>
#include <fstream.h>
int main ()
{
Subject: OOP (C++) Print Date: 16-10-2018 Page 2 of 6
ifstream myfile;
myfile.open ("galaxy.txt");
if(myfile.is_open())
{
Cout<<”\n\tFile is Open Sucessfully ….”);
Myfile.close();
}
else
{
Cout<<”\n\tFile is Not Open Sucessfully ….”);
}
return 0;
}
Close The File,
When input and output operations on a file is over, then we must close it. So that resources become
available again for different operation.
We call the stream's member function close.
This member function takes flushes the associated buffers and closes the file:
file.close();
Writing Some Thing into the file.
We can write information to a file from your program using the stream insertion operator (<<).
The use of << operator is same as we use with cout object.
But when << operator is used for file then it needs object of ofstream or fstream class object.
Example : fout<<”Message”;
Reading Some Thing into the file.
We can read information from a file from your program using the stream extraction operator (>>).
The use of >> operator is same as we use with cin object.
But when >> operator is used for file then it needs object of ifstream or fstream class object.
Example : fout >>string;
Input And Output Operation
Using put() and get() function
The function put() writes a single character to the associated stream.
Similarly, the function get() reads a single character form the associated stream.
Example : file.get(ch); file.put(ch);
Using write() and read() function
write() and read() functions write and read blocks of binary data.
Example: file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));
File pointers and their manipulation
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.
Subject: OOP (C++) Print Date: 16-10-2018 Page 3 of 6
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:
seekg() and seekp() Member Functions.
These functions allow to change the location of the get and put positions.
Both functions are overloaded with two different prototypes.
seekg() : Moves get pointer(input) to a specified location
seekp() : Moves put pointer (output) to a specified location
Example No 1 : seekg( position ); seekp( position );
Using this functions, stream pointer changed to the given fixed position.
It start counting from the beginning of file.
Example No 2 : seekg ( offset, direction ); seekp ( offset, direction );
Using this functions, the get or put position is set to an offset value relative to some specific point
determined by the parameter direction.
offset is of type streamoff. and
o The parameter offset represents the number of bytes the file pointer is to be moved from the
location specified by the parameter refposition.
direction is of type seekdir, which is an enumerated type that determines the point from where offset
is counted from.
o direction is one of the following values:
o ios::beg : From the start of the file
o ios::cur : From the current position of the pointer
o ios::end : From the end of the file
o Example : file.seekg(-10, ios::cur);
tellg() and tellp() Member Functions
tellg() and tellp() are member functions with no parameters
They return a value of the member type streampos,
tellg() : Gives the current position of the get pointer
tellp() : Gives the current position of the put pointer.
Basic operation on text file
Program to write in a text file
#include int main()
{
ofstream fout;
fout.open("out.txt");
char str[300]="Galaxy Computer Education is the programmers Choice";
fout << str;
fout.close();
return 0;
}
Program to read from text file and display it
#include int main()
Subject: OOP (C++) Print Date: 16-10-2018 Page 4 of 6
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout << ch;
}
fin.close();
return 0;
}
Program to count number of characters.
#include int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
int count=0;
while(!fin.eof())
{
fin.get(ch); count++;
}
cout << "Number of characters in file is " << count;
fin.close();
return 0;
}
Program to count number of words
#include int main()
{
ifstream fin;
fin.open("out.txt");
char word[30];
int count=0;
while(!fin.eof())
{
fin >> word;
count++;
}
cout << "Number of words in file is " << count;
fin.close();
return 0;
}
Program to count number of line
#include int main()
{
ifstream fin;
fin.open("out.txt");
char str[80];
int count=0;
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
cout << "Number of lines in file is " << count;
fin.close();
return 0;
}
Subject: OOP (C++) Print Date: 16-10-2018 Page 5 of 6
Program to copy contents of file to another file.
#include int main()
{
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout << ch;
}
fin.close();
fout.close();
return 0;
}
Subject: OOP (C++) Print Date: 16-10-2018 Page 6 of 6