Reading and writing to Files

File handling in C++ allows you to work with files on your computer's storage. You can read data from files, write data to files, and perform various operations like creating, opening, closing, and deleting files.

Basic File Operations

Opening a File

To work with a file in C++, you first need to open it. You can do this using the ifstream (input file stream) for reading and ofstream (output file stream) for writing.

				
					#include <iostream>
#include <fstream>

int main() {
    std::ifstream inFile; // Input file stream
    inFile.open("example.txt"); // Open the file

    // Check if the file is opened successfully
    if (!inFile) {
        std::cerr << "Unable to open file";
        return 1; // Exit the program with an error
    }

    // File is opened successfully, you can now read from it

    inFile.close(); // Don't forget to close the file when done
    return 0;
}

				
			

Explanation:

  • We include the necessary header files <iostream> and <fstream> for input and output stream operations and file handling respectively.
  • An ifstream object inFile is declared to handle input operations.
  • We use the open() member function to open the file named “example.txt” in the current directory.
  • Error handling is performed to check if the file is opened successfully. If not, an error message is displayed, and the program exits with a return code of 1.
  • Once the file is successfully opened, operations like reading from it can be performed.
  • Finally, the file is closed using the close() member function.

Reading from a File

Once the file is successfully opened, you can read data from it. The most common way to do this is by using input stream operators (>>) to extract data from the file.

				
					#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream inFile; // Input file stream object
    inFile.open("example.txt"); // Open the file

    if (!inFile) {
        std::cerr << "Unable to open file";
        return 1;
    }

    std::string data;
    while (inFile >> data) { // Read data from file
        std::cout << data << std::endl; // Output data to console
    }

    inFile.close(); // Close the file
    return 0;
}

				
			
				
					// output //
This
is
an
example
file.

				
			

Explanation:

  • We continue with the file handling process by opening the “example.txt” file for reading.
  • Inside the while loop, data is read from the file using the input stream operator >>. This reads the data word by word, separated by whitespace, and stores it in the string variable data.
  • Each word read from the file is then printed to the console using cout.
  • The loop continues until the end of the file is reached.
  • Finally, the file is closed.

This output demonstrates that the contents of the “example.txt” file were successfully read and printed to the console, each word on a new line.

Writing to a File

Similarly, you can write data to a file using the ofstream class and output stream operators (<<).

				
					#include <iostream>
#include <fstream>

int main() {
    std::ofstream outFile; // Output file stream object
    outFile.open("output.txt"); // Open (or create) the file named "output.txt"

    if (!outFile) {
        std::cerr << "Unable to create file";
        return 1;
    }

    outFile << "Hello, world!\n"; // Write data to the file
    outFile << "This is a new line.";

    outFile.close(); // Close the file
    return 0;
}

				
			
				
					// output //
Hello, world!
This is a new line.

				
			

Explanation:

  • Here, we use the ofstream object outFile to handle output operations.
  • The open() member function is used to create or open the file named “output.txt” in the current directory for writing.
  • Error handling checks if the file is created or opened successfully. If not, an error message is displayed, and the program exits with a return code of 1.
  • Data is written to the file using the output stream operator <<. In this case, we’re writing the string “Hello, world!\n” followed by “This is a new line.” to the file.
  • After writing the data, the file is closed using the close() member function.

After running the program, you’ll find a file named “output.txt” in the same directory with the following content:

Advanced File Operations

Checking End-of-File (EOF)

You can check if you have reached the end of a file while reading from it using the eof() function.

				
					#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream inFile;
    inFile.open("example.txt");

    if (!inFile) {
        std::cerr << "Unable to open file";
        return 1;
    }

    std::string data;
    while (!inFile.eof()) {
        inFile >> data;
        std::cout << data << std::endl;
    }

    inFile.close();
    return 0;
}

				
			

Appending to a File

You can append data to an existing file by opening it in append mode (std::ios::app).

				
					#include <iostream>
#include <fstream>

int main() {
    std::ofstream outFile;
    outFile.open("output.txt", std::ios::app);

    if (!outFile) {
        std::cerr << "Unable to open file";
        return 1;
    }

    outFile << "\nAppending new data.";

    outFile.close();
    return 0;
}

				
			

Reading and Writing Binary Files

In addition to text files, you can also work with binary files in C++. Binary files store data in a format that is not human-readable but is more efficient for certain types of data.

				
					#include <iostream>
#include <fstream>

struct Person {
    char name[50];
    int age;
};

int main() {
    Person p1 = {"John", 25};

    // Writing to a binary file
    std::ofstream outFile("people.bin", std::ios::binary);
    outFile.write(reinterpret_cast<char*>(&p1), sizeof(Person));
    outFile.close();

    // Reading from a binary file
    Person p2;
    std::ifstream inFile("people.bin", std::ios::binary);
    inFile.read(reinterpret_cast<char*>(&p2), sizeof(Person));
    inFile.close();

    std::cout << "Name: " << p2.name << ", Age: " << p2.age << std::endl;

    return 0;
}

				
			
				
					// output //
Name: John, Age: 25

				
			

File handling in C++ is a powerful feature that allows you to work with files effectively. You can read data from files, write data to files, and perform various operations on files. Understanding file handling is essential for many real-world applications where data needs to be stored and manipulated. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India