Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views11 pages

File Handling in C

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 11

FILE HANDLING IN C++

File handling in C++

The files handled so far have all been temporary files (data files); the data created by these files
could not be stored for later use. The data could not be used by other programs created later.

These files use the iostream standard library, which provides cin and cout methods for reading
from standard input and writing to standard output respectively.

C++ however provides a way or a mechanism for creating files which can s tore data
permanently, data which can be saved on disk and then used later. These files allow data to be
stored permanently and also allow transfer of input - data or output - data from one computer
to another to be easily done by using files.

To read and write to or from such files requires another standard C++ library called fstream,
which defines three new data types:

Sr.No Data Type & Description

1 ofstream

This data type represents the output file stream and is used to create files and to
write information to files. This class signifies the output file stream and is applied
to create files for writing information to files.

2 ifstream

This data type represents the input file stream and is used to read information
from files. It signifies the input file stream and is applied for reading information
from files.

3 fstream

This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files,
and read information from files. This Stream class can be used for both read and

Page 1 of 11
FILE HANDLING IN C++
write from/to files.

To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.

How to achieve File Handling

For achieving file handling in C++ we need follow following steps

 Naming a file
 Opening a file
 Reading data from file
 Writing data into file
 Closing a file

Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And ifstream object is
used to open a file for reading purpose only.

Page 2 of 11
FILE HANDLING IN C++
Before performing any operation on a file, you must first open it. If you need to write to the file,
open it using fstream or ofstream objects. If you only need to read from the file, open it using the
ifstream object.

The three objects, that is, fstream, ofstream, and ifstream, have the open() function defined in
them. The function takes this syntax:

open (“fileName”, ios::mode);

Here, fileName specifies the name and location of the file to be opened and mode defines the
mode in which the file should be opened. The mode parameter is optional. It can take any of the
following values:

Sr.No Mode Flag & Description

1 ios::app

Append mode. All output to that file to be appended to the end. All output
operations are performed at the end of the file, appending the content to the
current content of the file.

2 ios::ate

Open a file for output and move the read/write control to the end of the file. 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.

3 ios::in

Open a file for reading.

4 ios::out

Page 3 of 11
FILE HANDLING IN C++
Open a file for writing.

5 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. If the file already exists, its
contents will be truncated before opening the file.

6 ios::binary

Open in binary mode.

You can combine two or more of these values by ORing them together. For example if you
want to open a file in write mode and want to truncate it in case that already exists, following
will be the syntax:

ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
In an similar way, you can open a file for reading and writing purpose as follows −

fstream afile;
afile.open("file.dat", ios::out | ios::in );

or

ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);

Each of the open member functions of classes ofstream, ifstream and fstream has a default mode
that is used if the file is opened without a second argument:

class default mode parameter


ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out

Page 4 of 11
FILE HANDLING IN C++

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively
assumed, even if a mode that does not include them is passed as second argument to
the open member function (the flags are combined).

For fstream, the default value is only applied if the function is called without specifying any
value for the mode parameter. If the function is called with any value in that parameter the
default mode is overridden, not combined.

File streams opened in binary mode perform input and output operations independently of any
format considerations. Non-binary files are known as text files, and some translations may occur
due to formatting of some special characters (like newline and carriage return characters).

Closing a File
When we are finished with our input and output operations on a file we shall close it so that the
operating system is notified and its resources become available again. For that, we call the
stream's member function close. This member function takes flushes the associated buffers and
closes the file:

myfile.close();
Once this member function is called, the stream object can be re-used to open another file, and
the file is available again to be opened by other processes.

In case that an object is destroyed while still associated with an open file, the destructor
automatically calls the member function close.

Writing to a File
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the screen.
The only difference is that you use an ofstream or fstream object instead of the cout object.

Page 5 of 11
FILE HANDLING IN C++
#include <iostream>
#include <fstream>
using namespace std;

int main ()
{
ofstream myfile;
myfile.open("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}

Reading from a File


You read information from a file into your program using the stream extraction operator (>>)
just as you use that operator to input information from the keyboard. The only difference is that
you use an ifstream or fstream object instead of the cin object.

Read and Write Example


Following is the C++ program which opens a file in reading and writing mode. After writing
information entered by the user to a file named afile.dat, the program reads information from
the file and outputs it onto the screen:

Text files
Text file streams are those where the ios::binary flag is not included in their opening mode.
These files are designed to store text and thus all values that are input or output from/to them can
suffer some formatting transformations, which do not necessarily correspond to their literal
binary value.
Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.

When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide the least security and
takes bigger storage space.

Page 6 of 11
FILE HANDLING IN C++
Binary files

Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they
store it in the binary form (0's and 1's).
They can hold a larger amounts of data, are not readable easily, and provides better security than
text files.

Writing operations on text files are performed in the same way we operated with cout:

#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}

Reading from a file can also be performed in the same way that we did with cin:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}

Page 7 of 11
FILE HANDLING IN C++
myfile.close();
}

else cout << "Unable to open file";

return 0;
}

This last example reads a text file and prints out its content on the screen. We have created a
while loop that reads the file line by line, using getline. The value returned by getline is a
reference to the stream object itself, which when evaluated as a Boolean expression (as in this
while-loop) is true if the stream is ready for more operations, and false if either the end of the file
has been reached or if some other error occurred.

Reading data from the keyboard and writing it to a file

#include <iostream>

#include <fstream>

using namespace std;

int main()

string studNum, studName;

double mark;

ofstream outFile;

outFile.open("myFile.txt");

if(outFile.is_open())

cout<<"Enter student number ";

cin>>studNum;

outFile<<studNum<<endl;

Page 8 of 11
FILE HANDLING IN C++
cout<<"Enter student name ";

cin>>studName;

outFile<<studName<<endl;

cout<<"Enter mark ";

cin>>mark;

outFile<<mark<<endl;

cout << "\nFile contents written successfully \n";

else

cout<<"File does not exist or is not open";

outFile.close();

return 0;

Appending a file

#include <iostream>

#include <fstream>

using namespace std;

int main()

string line = "jumped over the lazy dog";

ofstream appFile("thisFile.txt", ios::out|ios::app);

if(appFile.is_open())

appFile<<line ;
Page 9 of 11
FILE HANDLING IN C++
cout<<" File appended successfully \n";

else

printf("File does not exist");

appFile.close();

return 0;

Checking state flags


The following member functions exist to check for specific states of a stream (all of them return
a bool value):

bad()

Returns true if a reading or writing operation fails. For example, in the case that we try to
write to a file that is not open for writing or if the device where we try to write has no
space left.

fail()

Returns true in the same cases as bad(), but also in the case that a format error happens,
like when an alphabetical character is extracted when we are trying to read an integer
number.

eof()

Returns true if a file open for reading has reached the end.

good()

It is the most generic state flag: it returns false in the same cases in which calling any of
the previous functions would return true. Note that good and bad are not exact opposites
(good checks more state flags at once).

The member function clear() can be used to reset the state flags.

Page 10 of 11
FILE HANDLING IN C++
Functions use in File Handling

Function Operation

open() To create a file

close() To close an existing file

get() Read a single character from a file

put() write a single character in file.

read() Read data from file

write() Write data into file.

Page 11 of 11

You might also like