C++ · C++ Beginner

File Handling in C++

Run this in the Online C++ compiler

Introduction

Hello Coders!

From reading to writing, understanding File Handling in C++ is pivotal for creating applications that can store and retrieve information efficiently. Join us on this journey to master the art of managing files and expand the capabilities of your C++ programs.

Reading and Writing Files using fstream

C++ provides the fstream library for handling file input and output operations. You can use ifstream for reading from a file, ofstream for writing to a file, and fstream for both.

Here's an example demonstrating how to create, write to, and read from a file:

#include
#include
#include

int main() {
    // Creating and writing to a file
    std::ofstream outputFile("example.txt");

    if (outputFile.is_open()) {
        outputFile << "Hello, C++ File Handling!" << std::endl;
        outputFile << "This is a new line." << std::endl;
        outputFile.close();
        std::cout << "File created and written successfully." << std::endl;
    } else {
        std::cerr << "Unable to open the file for writing." << std::endl;
        return 1; // Exit with an error code
    }

    // Reading from a file
    std::ifstream inputFile("example.txt");

    if (inputFile.is_open()) {
        std::cout << "Contents of the file:" << std::endl;
        std::string line;
        while (std::getline(inputFile, line)) {
            std::cout << line << std::endl;
        }
        inputFile.close();
    } else {
        std::cerr << "Unable to open the file for reading." << std::endl;
        return 1; // Exit with an error code
    }

    return 0;
}

In this example, a file named "example.txt" is created, and two lines of text are written to it. Then, the file is opened for reading, and its contents are printed to the console.

Exercise: Perform File Operations

Now, let's perform file operations by creating, writing to, and reading from a file.

Conclusion

Feel free to modify the program to include more interactive elements or create a different program based on your interests. This exercise will help you practice file handling in C++.

Navigating the intricacies of File Handling in C++ empowers you with the ability to seamlessly manage and manipulate data stored persistently. Happy coding!

This website uses cookies to ensure you get the best experience on our website.