Professional Documents
Culture Documents
File Handling in C++
File Handling in C++
File Handling in C++
Output:
Open a File
Previous program writes data to a file, so we open the file for output (or for
writing) by creating an ofstream object.
Two arguments are passed to the object’s constructor (line 11)—the filename and
the file-open mode.
Main purpose of the constructor in C++ is to construct an object of the class. In
other words, it is used to initialize all class data members.
Its like a member function of a class.
For an ofstream object, the file-open mode can be either ios::out (the default) to
output data to a file or ios::app to append data to the end of a file.
We create an ofstream object named outClientFile associated with the file
clients.txt that’s opened for output.
because we did not specify a path to the file (that is, it’s location), the file will be in
the same directory as the program.
The ofstream opens the file— this establishes a “line of communication” with the
file.
Since ios:: out is the default argument, so we can write the statement as:
ofstream outClientFile{"clients.txt"};
If the specified file does not yet exist, then the ofstream object creates the file,
using that filename.
File-open Modes
• Since ios::out write to the file, so there are chances of data loss
in the file. Create a backup of file before opening it this mode.
Opening a File via the open
You can create an ofstream object without opening a specific file, i.e.,
a file can be attached to the object later.
ofstream outClientFile;
creates an ofstream object that’s not yet associated with a file. The
ofstream member function open opens a file and attaches it to an
existing ofstream object as
outClientFile. open("clients.txt",ios::out);
Check whether the open operation is successful (see the lines 14-17 in
the previous program). Reasons for failure could be :
attempting to open a nonexistent file for reading
attempting to open a file for reading or writing from a directory that you don’t
have permission to access, and
opening a file for writing when no disk space is available.
Processing Data
If file opens successfully, the program begins processing data. program
prompts the user to enter either the various fields for each record or the end-
of-file indicator when data entry is complete.
Output
read(), write(), put() and get() functions
read(): reads a block of code from a file.
write(): writes a block f code into the file.
put(): puts a single character in a file.
get(): reads a single character from a file.
Random-Access Files
Sequential files are inappropriate for instant-access applications, in
which a particular record must be located immediately.
Common instant-access applications are airline reservation
systems, banking systems, point-of-sale systems that require rapid
access to specific data.
Individual records of a random-access file can be accessed directly
(and quickly) without having to search other records.
Data can be inserted into a random-access file without destroying
other data in the file. Data stored previously also can be updated or
deleted without rewriting the entire file.
Creating a Random-Access Files
The ostream member function write() outputs to the specified
stream a fixed number of bytes, beginning at a specific location in
memory.
When the stream is associated with a file, function write() writes
the data at the location in the file specified by the put file-position
pointer.
The istream member function read() inputs a fixed number of
bytes from the specified stream to an area in memory beginning at
a specified address. If the stream is associated with a file, function
read() inputs bytes at the location in the file specified by the “get”
file-position pointer.
File-Position Pointers
Programs normally read sequentially from the beginning of a file and
read all the data consecutively until the desired data is found.
Once you have a file open, you can navigate to different parts of the
file. This is often referred to as random access of files.
We can change the read and write position of the file.
istream and ostream provide member functions— seekg(“seek get”)
and seekp(“seek put”), respectively—to reposition the file-position
pointer.
Each istream (ostream) object has a get (put) pointer, which indicates
the byte number in the file from which the next input (output) is to
occur.
The statement, inClientFile.seekg(0); , repositions the file-position
pointer to the beginning of the file (location 0).
File-Position Pointers
A second argument can be specified to indicate the seek direction, which can
be ios::beg (the default) for positioning relative to the beginning of a stream.
seekg(50, ios::beg); will set the put pointer to 50 bytes from the begining of
the file and start reading the data.
seekg(50, ios::cur); will set the put pointer to 50 bytes from the current
location of the file.
seekg(-50, ios::end); will set the put pointer to 50 bytes before the end of the
file.
Same arguments are used in seekp() for writing the data in the file.
Detecting End-of-File
When we read a file, as we do here, we will eventually
encounter an end-of-file (EOF) condition. The EOF is a
signal sent to the program from the operating system when
there is no more data to read.
int main()
{
const int MAX = 80; //size of buffer
char buffer[MAX]; //character buffer
ifstream infile(“TEST.TXT”); //create file for input
while( !infile.eof() ) //until end-of-file
{
infile.getline(buffer, MAX); //read a line of text
cout << buffer << endl; //display it
}
return 0;
}
Example: seekp()& seekg()
Write the following text in brain.txt file and save it.
Hello|Hello
Hi|Hello
Who are you|I am a new employee
whats up|Hello
Output:
10 from Beginning = llo
5 from Current= Hello
-10 from End = up|Hello
seekp()
//output file stream
ofstream outfile;
//open the file
//use ios::in and ios::out to ensure seekp does not replace all text
outfile.open("F:\\brain.txt", ios::in|ios::out);
string insertText = "I can't do that, Hal";
outfile.seekp(12, ios::beg);
outfile << insertText << endl;
Output: