How To Work With File handling in C++?

Last updated on Aug 02,2024 222.3K Views

How To Work With File handling in C++?

edureka.co

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.

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:

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 :

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:

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:

 

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:

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.

Check the File for Errors

In file handling, it’s important to ensure the file was opened without any error before we can perform any further operations on it.
There are three commonly used ways to check files for errors:

1. By Checking the File Object

ofstream my_file("name.txt");

// check if the file has been opened properly
if (!my_file) {

    // print error message
    cout << "Error while opening the file." << endl;

    // terminate the main() function
    return 0;
}

Notice the condition in the if statement:

if (!my_file) {…}
This method checks if the file is in an error state by evaluating the file object itself.
If the file opens successfully, the condition evaluates to true.
If an error is found, it is evaluated to false, and you can handle the error accordingly.
Note This method is recomended
2. Using the is_open() Function
The is_open() function is a boolean function that returns
true – if the file was opened successfully.
false -if the file was unable to be opened.
For instance,

ofstream my_file("name.txt");

if (!my_file.is_open()) {
    cout << "Error while opening the file." << endl;
    return 0;
}

3. Using the fail() Function
The fail() function returns
true – if the file was unable to open.
false – if the file was opened without error.

ofstream my_file("name.txt");

if (my_file.fail()) {
    cout << "Error while opening the file." << endl;
    return 0;
}

Append to a Text File

If you open the file in append mode then you can add text to it and append it.
In C++, you can achieve this by using the ios::app flag when opening the file:
ofstream my_file(“example.txt”, ios::app);

Currently we only have this text in our example.txt
line1
Line2
Line3
Now, let’s add some more text to example.txt:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    // open a text file for appending
    ofstream my_file("example.txt", ios::app);

    // if the file doesn't open successfully, print an error message
    if(!my_file) {
        cout << "Failed to open the file for appending." << endl;
        return 1;  
    }
    // append multiple lines to the file
    my_file << "Line 4" << endl;
    my_file << "Line 5" << endl;
    my_file << "Line 6" << endl;

    // close the file
    my_file.close();

    return 0;
}

The above code will append the lines below to our existing content example.txt:
Line 4
Line 5
Line 6
Now, let’s see what our example.txt looks like, output is shown below.

File Handling With fstream

File handling in C++ refers to the process of creating and reading/writing from a file.
We can access various file handling methods in C++ by importing the class.
#include
includes two classes for file handling:
ifstream – to read from a file.
ofstream – to create/open and write to a file
It combines the functionalities of ifstream (for input) and ofstream (for output) into a single class
Let’s understand this with examples
Opening a File with fstream
To work with files using fstream, you typically start by opening a file. Here’s how you can open a file for reading and writing using fstream:

#include <iostream>
#include <fstream>


int main() {
    // Opening a file named "example.txt" in read-write mode
    std::fstream file("example.txt", std::ios::in | std::ios::out);


    if (!file.is_open()) {
        std::cerr << "Failed to open the file.n";
        return 1;
    }


    // Perform read and write operations here


    file.close(); // Always close the file when done
    return 0;
}

Writing to a File with fstream

You can write data to a file using the > operator or the read() function. Here’s an example of reading from a file using fstream:

#include <iostream>
#include <fstream>


int main() {
    std::fstream file("example.txt", std::ios::in);


    if (!file.is_open()) {
        std::cerr << "Failed to open the file.n";
        return 1;
    }


    std::string line;
    while (std::getline(file, line)) {
        std::cout << "Read from file: " << line << std::endl;
    }


    file.close(); // Always close the file when done
    return 0;
}

Checking for Errors with fstream

It’s important to check for errors when working with files. Use the bad() function to check if an error occurred during file operations:

#include <iostream>
#include <fstream>


int main() {
    std::fstream file("example.txt", std::ios::in | std::ios::out);


    if (!file.is_open()) {
        std::cerr << "Failed to open the file.n";
        return 1;
    }


    // Perform operations...


    if (file.bad()) {
        std::cerr << "Error occurred during file operations.n";
        return 1;
    }


    file.close(); // Always close the file when done
    return 0;
}

fstream in C++ provides a flexible way to handle files, allowing both input and output operations seamlessly. Ensure to handle file opening, reading, writing, and error checking to create robust file handling mechanisms in your applications.

FAQs

1. How to file handle in C++?

File handling in C++ is performed with the help of classes from the fstream library: ifstream, ofstream, fstream. You declare an object of a proper file stream class. Then, using open() with the proper modes like ios::in to read a file, ios::out to write, ios::app to append to the file, perform the operations needed, and close a file by the close() method.

2.How does file handling work?
C++ file handling is based on the stream-based model. It creates a bridge between your program and the file on the disk. Most of the time, this link will be managed through objects of type ifstream, ofstream, or fstream. There are methods in these stream classes to read, write, and manipulate the content of the file. Mode is usually specified at the time a file is opened. This informs whether you want to read, write, or append to the file. The input/ output operations, like>, getline(), which transfer data between your program and the file. Once the file operations are done, the file is closed, which releases the system resources.

3.What are the modes of file handling C++?
The various modes of dealing with files in C++ are realized using the flags defined in the class ios. They include:

ios::in; //For input
ios::out; //For output
ios::app; //Append; all output to that file goes to the end.
ios::ate; //Open with the file pointer at end-of-file.
ios::trunc; //If the file already exists, its contents are truncated; that is, destroyed.
These flags can be combined using the bitwise OR operator [|] for combinations of functionalities like ios::in | ios::binary for binary file reads. These flags control the access and editing of files when performing any file-handling operation in C++.

4 What is the syntax of a file in C++?
#include
fstream file;
file.open(“filename.txt”, ios::in | ios::out);
file > data; // Read data
file.close();

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.

BROWSE COURSES