Whether it is the programming world or not, files are vital as they store data.
This
article discuss working of file handling in C++. Following pointers will be covered in
the article,
Opening a File
Writing to a File
Reading from a File
Close a File
File Handling In C++
Files are used to store data in a storage device permanently. File handling provides
a mechanism to store the output of a program in a file and to perform various
operations on it.
A stream is an abstraction that represents a device on which operations of input
and output are performed. A stream can be represented as a source or destination
of characters of indefinite length depending on its usage.
In C++ we have a set of file handling methods. These include ifstream, ofstream,
and fstream. These classes are derived from fstrembase and from the
corresponding iostream class. These classes, designed to manage the disk files, are
declared in fstream and therefore we must include fstream and therefore we must
include this file in any program that uses files.
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.
ofstream: This Stream class signifies the output file stream and is applied to
create files for writing information to files
ifstream: This Stream class signifies the input file stream and is applied for
reading information from files
fstream: This Stream class can be used for both read and write from/to files.
All the above three classes are derived from fstreambase and from the
corresponding iostream class and they are designed specifically to manage disk
files.
C++ provides us with the following operations in File Handling:
Creating a file: open()
Reading data: read()
Writing new data: write()
Closing a file: close()
Moving on with article on File Handling in C++
Opening a File
Generally, the first operation performed on an object of one of these classes is to
associate it to a real file. This procedure is known to open a file.
We can open a file using any one of the following methods:
1. First is bypassing the file name in constructor at the time of object creation.
2. Second is using the open() function.
To open a file use
1 open() function
Syntax
1 void open(const char* file_name,ios::openmode mode);
Here, the first argument of the open function defines the name and format of the
file with the address of the file.
The second argument represents the mode in which the file has to be opened. The
following modes are used as per the requirements.
Modes Description
Opens the file to read(default for
In
ifstream)
Opens the file to write(default for
Out
ofstream)
Opens the file and appends all the
App
outputs at the end
Opens the file and moves the control to
Ate
the end of the file
Trunk Removes the data in the existing file
nocreate Opens the file only if it already exists
Example
1 fstream new_file;
2 new_file.open(“newfile.txt”, ios::out);
In the above example, new_file is an object of type fstream, as we know fstream is a
class so we need to create an object of this class to use its member functions. So
we create new_file object and call open() function. Here we use out mode that
allows us to open the file to write in it.
Default Open Modes :
ifstream ios::in
ofstream ios::out
fstream ios::in | ios::out
We can combine the different modes using or symbol | .
Example
ofstream new_file;
1 new_file.open(“new_file.txt”, ios::out | ios::app );
Here, input mode and append mode are combined which represents the file is
opened for writing and appending the outputs at the end.
As soon as the program terminates, the memory is erased and frees up the
memory allocated and closes the files which are opened.
But it is better to use the close() function to close the opened files after the use of
the file.
Using a stream insertion operator << we can write information to a file and using
stream extraction operator >> we can easily read information from a file.
Example of opening/creating a file using the open() function
1 #include<iostream>
2 #include <fstream>
using namespace std;
3
int main()
4 {
5 fstream new_file;
6 new_file.open("new_file",ios::out);
7 if(!new_file)
8 {
9 cout<<"File creation failed";
10 }
11 else
{
12 cout<<"New file created";
13 new_file.close(); // Step 4: Closing file
14 }
15 return 0;
16 }
17
18
Output:
Explanation
In the above example we first create an object to class fstream and name it
‘new_file’. Then we apply the open() function on our ‘new_file’ object. We give the
name ‘new_file’ to the new file we wish to create and we set the mode to ‘out’ which
allows us to write in our file. We use a ‘if’ statement to find if the file already exists
or not if it does exist then it will going to print “File creation failed” or it will gonna
create a new file and print “New file created”.
Moving on with article on File Handling in C++
Writing to a File
Example:
1 #include <iostream>
2 #include <fstream>
3 using namespace std;
4 int main()
5 {
6 fstream new_file;
7 new_file.open("new_file_write.txt",ios::out);
8 if(!new_file)
9 {
10 cout<<"File creation failed";
11 }
12 else
13 {
14 cout<<"New file created";
15 new_file<<"Learning File handling"; //Writing to file
16 new_file.close();
17 }
18 return 0;
19 }
Output:
Explanation
Here we first create a new file “new_file_write” using open() function since we
wanted to send output to the file so, we use ios::out. As given in the program,
information typed inside the quotes after Insertion Pointer “<<” got passed to the
output file.
Moving on with this article on File Handling in C++
Reading from a File
Example
1
2 #include <iostream>
#include <fstream>
3 using namespace std;
4 int main()
5 {
6 fstream new_file;
7 new_file.open("new_file_write.txt",ios::in);
8 if(!new_file)
9 cout<<"No such file"; } else { char ch; while (!new_file.eof()) { new_file >>ch;
10 cout << ch;
11 }
new_file.close();
12
return 0;
13 }
14
Output:
Explanation
In this example, we read the file that generated id previous example i.e.
new_file_write.
To read a file we need to use ‘in’ mode with syntax ios::in. In the above example, we
print the content of the file using extraction operator >>. The output prints without
any space because we use only one character at a time, we need to use getline()
with a character array to print the whole line as it is.
Close a File
It is simply done with the help of close() function.
Syntax: File Pointer.close()
Example
1 #include <iostream>
2 #include <fstream>
3 using namespace std;
4 int main()
5 {
6 fstream new_file;
7 new_file.open("new_file.txt",ios::out);
8 new_file.close();
9 return 0;
10 }
Output:
The file gets closed.
Special operations in a File
There are few important functions to be used with file streams like:
tellp() - It tells the current position of the put pointer.
Syntax: filepointer.tellp()
tellg() - It tells the current position of the get pointer.
Syntax: filepointer.tellg()
seekp() - It moves the put pointer to mentioned location.
Syntax: filepointer.seekp(no of bytes,reference mode)
seekg() - It moves get pointer(input) to a specified location.
Syntax: filepointer.seekg((no of bytes,reference point)
put() - It writes a single character to file.
get() - It reads a single character from file.
Note: For seekp and seekg three reference points are passed: ios::beg -
beginning of the file ios::cur - current position in the file ios::end - end
of the file
#include <iostream>
#include<conio>
#include <fstream>
using namespace std;
int main()
fstream st; // Creating object of fstream class
st.open("E:\studytonight.txt",ios::out); // Creating new file
if(!st) // Checking whether file exist
cout<<"File creation failed";
else
{
cout<<"New file created"<<endl;
st<<"Hello Friends"; //Writing to file
// Checking the file pointer position
cout<<"File Pointer Position is "<<st.tellp()<<endl;
st.seekp(-1, ios::cur); // Go one position back from current position
//Checking the file pointer position
cout<<"As per tellp File Pointer Position is "<<st.tellp()<<endl;
st.close(); // closing file
st.open("E:\studytonight.txt",ios::in); // Opening file in read mode
if(!st) //Checking whether file exist
cout<<"No such file";
else
{
char ch;
st.seekg(5, ios::beg); // Go to position 5 from begning.
cout<<"As per tellg File Pointer Position is "<<st.tellg()<<endl; //Checking file
pointer position
cout<<endl;
st.seekg(1, ios::cur); //Go to position 1 from beginning.
cout<<"As per tellg File Pointer Position is "<<st.tellg()<<endl; //Checking file
pointer position
st.close(); //Closing file
getch();
return 0;
Output
New file created
File Pointer Position is 13
As per tellp File Pointer Position is 12
As per tellg File Pointer Position is 5
As per tellg File Pointer Position is 6