File Handling in C++


Illustration showing file handling operations in C++

What is File Handling?

The technique for creating and carrying out read and write operations on a file in C++ is known as file handling. By importing the class, we may access several C++ file handling functions. File management makes persistent data storage possible by enabling us to save and retrieve data from secondary storage.

A stream refers to a flow of bytes used to perform input and output operations. In C++, standard input and output are handled by stream objects such as cin and cout, which are defined in the <iostream> library.

For file handling, C++ provides the <fstream> header, which includes the following classes:

  • ifstream: for reading from files
  • ofstream: for writing to files
  • fstream: for both reading from and writing to files

In C++, handling a file involves three primary steps: opening the file, carrying out read/write operations, and closing the file. Before reading or writing may begin, a file must be opened. In C++, files are opened using stream objects, such as fstream file("file.txt", mode); where the mode defines the operation (read, write, etc.).

File opening modes in C++ define how a file is accessed. Common modes include:

  • ios::in → Opens the file for reading
  • ios::out → Opens the file for writing
  • ios::binary → Opens the file in binary mode
  • ios::ate → Opens the file and moves the cursor to the end
  • ios::app → Opens the file in append mode; data is written at the end
  • ios::trunc → Truncates the file if it already exists (clears its contents)

Simple Example of File Opening Modes in C++:

  
fstream file("file.txt", ios::in);          //Read
fstream file("file.txt", ios::out);        //Write
fstream file("file.txt", ios::in | ios::out); //Read or Write
  

Note:ifstream and ofstream are two specialized file stream classes in C++.

Example: Writing to a File in C++

  
#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream file("hello.txt");
    file << "Welcome to Information System Department.";
    file.close(); //to free up resources and avoid data loss
    return 0;
}

Example: Reading content from a file

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
    ifstream file("hh.txt"); //Opening the file for reading
    string line;

    if (file.is_open()) {
        while (getline(file, line)) {
            cout << line;  
        }
        file.close();    //Closing the file 
    } else {
        cout << "Unable to open";
    }
    return 0;
}

Binary files in c++

Binary files store data in a raw, machine-readable format rather than human-readable text. They are usually more compact and efficient compared to text files, but their contents cannot be easily viewed or modified using regular text editors.

Binary files can be accessed in two main ways for reading and writing:

  • Sequential access starts at the beginning of the file and reads or writes data in a sequential manner. For jobs like analyzing log files or line-by-line reading of plain text files, this approach is perfect. It is less effective, though, when you need to look for certain content in big files.
  • Consider the following example that demonstrates writing to a file sequentially:

    
    #include <fstream>
    #include <iostream>
    using namespace std;
    int main() {
        ofstream file("hello.txt"); //ofstream is used for writing to files
        if (file.is_open()) {
            file << "first data.";
            cout << "Data written to file.";
            file.close();
        } else {
            cerr << "Error opening file.";
        }
        return 0;
    }
    
    • With random access, you can use search operations like seekg or seek get for reading or seekp or seek put for writing to go straight to a certain location in a file. For huge files, this approach is quicker and more effective, particularly when dealing with binary data.

    The example below demonstrates how to write to a file using random access:

    
    #include <fstream>
    #include <iostream>
    using namespace std;
    int main() {
        ifstream file("bb.txt");
        if (file.is_open()) {
            file.seekg(5, ios::beg); //Move pointer to the 5th byte from the beginning                          
            char ch;
            file.get(ch);or file >> ch; //Reading a single character
            cout <<"Character at position 5: " << ch;
            file.close();
        } else {
            cerr << "Error.";
        }
        return 0;
    }
    

Latest Posts


Getting Started with Java GUI

Getting Started with Java GUI

LetUsLearn May 28, 2025
File Handling in C++

File Handling in C++

LetUsLearn May 28, 2025
How to Configure Ad hoc Wireless Network.

How to Configure Ad hoc Wireless Network.

LetUsLearn May 28, 2025
Yilma Goshime

I’m committed to providing tailored solutions and always ready to assist if any issue arises.

LetUsLearn
Back to Top