How To Work With File handling in C++?

Last updated on Mar 29,2022 215.8K Views

How To Work With File handling in C++?

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,

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

open() function

Syntax

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.

ModesDescription

in

Opens the file to read(default for ifstream)

out

Opens the file to write(default for ofstream)

binary

Opens the file in binary mode

app

Opens the file and appends all the outputs at the end

ate

Opens the file and moves the control to the end of the file

trunc

Removes the data in the existing file

nocreate

Opens the file only if it already exists

noreplace

Opens the file only if it does not already exist

Example

fstream new_file;
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;

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

#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file; 
new_file.open("new_file",ios::out);  
if(!new_file) 
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing file
}
return 0;
}

Output:

Output-File Handling in C++- Edureka

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:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file; 
new_file.open("new_file_write.txt",ios::out);  
if(!new_file) 
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file<<"Learning File handling";    //Writing to file
new_file.close(); 
}   
return 0;
}

Output:

Output-File Handling in C++- Edureka

 

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

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file; 
new_file.open("new_file_write.txt",ios::in);   
if(!new_file) 
cout<<"No such file"; } else { char ch; while (!new_file.eof()) { new_file >>ch; 
cout << ch;   
}
new_file.close();    
return 0;
}

Output:

Output-File Handling in C++- Edureka

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.

Moving on with this article on File Handling in C++

Close a File

It is simply done with the help of close() function.

Syntax: File Pointer.close()

Example

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file; 
new_file.open("new_file.txt",ios::out);  
new_file.close();    
return 0;
}

Output:

The file gets closed.

Thus we have come to an end of this article on ‘File Handling in C++’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Comments
0 Comments

Join the discussion

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.