File Handling in C++: By: Haya Majid Qureshi BS (CS) - II
File Handling in C++: By: Haya Majid Qureshi BS (CS) - II
C++
By:
Haya Majid Qureshi
BS(CS)-II
Introduction
• Computer programs are associated to work with
files as it helps in storing data & information
permanently.
Files
istream class DATA ostream class
ACCESS TO FILE I/O
• ifstream
• ofstream
• fstream
The Stream Class Hierarchy
ios
Istream Ostream
iostream
Get() Put()
Read() Write()
>> <<
fstream
Ifstream Ofstream
Open() Open()
fstreambase Tellp()
Tellg()
Seekg() Seekp()
File Handling Hierarchy
DIFFERENT FILE OPERATION
• OPENING A FILE
• CLOSING A FILE
• READING FROM A FILE
• WRITING ON A FILE
• CHECKING FOR END OF FILE
OPENING A FILE
• For opening a file, we must first create a file
stream and than link it to the filename.
A file can be opened in two ways:
• Using the constructor function of the class.
This method is useful when we open only
one file in the stream.
using I).
Example :
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::trunc |ios::in);
USING CONSTRUCTOR
• A constructor that automatically calls
the open() member function and has the exact
same parameters as this member.
• operation in our previous example by writing:
outfile.put(ch);
• To read:
– get() – reading a single character .
– getline() – reading a single line.
infile.get(ch);
Stream Pointer
• All i/o file maintains atleast one internal pointers:
get _ pointer and put _ pointer
• They enable to attain the random access in file
otherwise which is sequential in nature.
infile.seekg(10);
Thus, the pointer will be pointing to the 11th byte in the file.
Contd…
• The other prototype for these functions is: