File Handling in C++

    Atul Kabra4 min readUpdated

    File handling in C++ lets your program read from and write to files on disk using the same stream interface you already know from std::cout and std::cin. The <fstream> header gives you std::ofstream for writing, std::ifstream for reading, and std::fstream for both. Because these are stream objects, << and >> work exactly as they do with the console.

    Here is the everyday workflow.

    Writing to a file

    Create an std::ofstream, write with <<, and let it close automatically.

    #include <fstream>
    #include <iostream>
    
    int main() {
        std::ofstream out{"students.txt"};   // opens (creates) the file
    
        if (!out) {                          // did it open?
            std::cerr << "Could not open file for writing\n";
            return 1;
        }
    
        out << "Asha,95\n";
        out << "Ravi,72\n";
        out << "Meera,88\n";
    
        // no explicit close needed — the destructor closes it (RAII)
    }
    

    Opening with ofstream truncates the file (starts fresh). To append instead, open with the append flag:

    std::ofstream out{"log.txt", std::ios::app};  // add to the end
    

    Reading a file line by line

    Use std::ifstream with std::getline to read one line at a time — the standard way to process text files.

    #include <fstream>
    #include <iostream>
    #include <string>
    
    int main() {
        std::ifstream in{"students.txt"};
    
        if (!in) {
            std::cerr << "Could not open file for reading\n";
            return 1;
        }
    
        std::string line;
        while (std::getline(in, line)) {     // loop ends at end-of-file
            std::cout << "Read: " << line << "\n";
        }
    }
    

    std::getline returns the stream, which converts to false when there is nothing left to read — so the while loop stops cleanly at the end of the file.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses

    Reading formatted values with >>

    When a file holds whitespace-separated values, >> parses them just like std::cin.

    #include <fstream>
    #include <iostream>
    
    int main() {
        std::ifstream in{"numbers.txt"};   // e.g. "10 20 30"
        int n;
        int total = 0;
        while (in >> n) {                  // reads ints until it fails
            total += n;
        }
        std::cout << "Sum: " << total << "\n";
    }
    

    Always check that the file opened

    A file may fail to open — wrong path, no permission, disk full. Test the stream right after opening (if (!in)), and check in.fail() or the loop condition while reading. Silently skipping a missing file is a common, hard-to-spot bug.

    Closing happens automatically

    You can call in.close(), but you rarely need to: when the stream object goes out of scope, its destructor closes the file. This is RAII again — the file is guaranteed to be closed even if an exception is thrown mid-function.

    A complete read-modify-write example

    A common task is to read records from one file, transform them, and write to another. Because both streams clean themselves up, the whole thing stays short and leak-free.

    #include <fstream>
    #include <iostream>
    #include <string>
    
    int main() {
        std::ifstream in{"students.txt"};
        std::ofstream out{"shout.txt"};
    
        if (!in || !out) {
            std::cerr << "Could not open one of the files\n";
            return 1;
        }
    
        std::string line;
        while (std::getline(in, line)) {
            // transform each line, then write it out
            for (char& c : line) {
                c = std::toupper(static_cast<unsigned char>(c));
            }
            out << line << "\n";
        }
        // both files close automatically at the end of main()
    }
    

    Notice both streams are checked together before any work begins — if either failed to open, the program reports it and stops rather than half-processing the data.

    Common mistakes

    • Not checking whether the file opened. Always test the stream (if (!out)) before relying on it.
    • Accidentally truncating a file. Plain ofstream wipes existing contents. Use std::ios::app to append.
    • Mixing >> and getline carelessly. >> leaves the newline in the buffer, so a following getline can read an empty line. Be deliberate about which you use.
    • Manually closing too early. Let RAII close the stream at scope exit unless you specifically need to reopen or release the file sooner.

    FAQ

    What is the difference between ifstream and ofstream? ifstream is an input file stream for reading; ofstream is an output file stream for writing. fstream can do both.

    Do I have to close a file manually? No. The stream's destructor closes it automatically when it goes out of scope. Manual close() is only needed for early release or reopening.

    Keep learning

    • File streams use the same <</>> as the rest of the I/O library — and getline returns std::string.
    • Combine file reading with error handling in Exception Handling in C++.
    • Browse the full series on the C++ OOP hub.

    Build real file-processing programs with mentors in Jalgaon — join the waitlist for our C++ Programming course.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses
    Atul Kabra

    Founder, Infoplanet

    Atul Kabra founded Infoplanet in 2001 and has spent over two decades teaching programming — C, C++, Java, databases and more — to students across Maharashtra.

    Related guides