TeachMate
My ProgressJoin Session

File Handling

0/6 completed · ~0h 24m

All Topics
C++LearnFile HandlingSyllabus
1 / 6

File Handling

intermediate
5 min read

What you'll learn

  • Open a file and check that it opened.
  • Write to and read from a text file.
  • Explain how RAII closes the file automatically.

File handling lets you read from and write to files.

Problem

Everything your program stores in variables disappears when it exits, but you want student records to still be there the next time you run the program.

Goal: Store the records in a file so they survive after the program ends.

Pseudocode
OPEN "students.txt" FOR WRITING
WRITE "Alice 87"
CLOSE

ON THE NEXT RUN
OPEN "students.txt" FOR READING
...

A file keeps data after the program ends. The rest of this note shows how to open, read, write, append to, and close files.

#include <fstream>
#include <iostream>

Writing to a File

std::ofstream outFile("output.txt");
if (outFile.is_open()) {
    outFile << "Hello, World!" << std::endl;
    outFile << 42 << std::endl;
    outFile.close();
}

Reading from a File

std::ifstream inFile("input.txt");
if (inFile.is_open()) {
    std::string line;
    while (std::getline(inFile, line)) {
        std::cout << line << std::endl;
    }
    inFile.close();
}

Reading Numbers

std::ifstream inFile("numbers.txt");
int num;
while (inFile >> num) {
    std::cout << num << " ";
}

File Modes

ModeDescription
ios::outWrite mode (default for ofstream)
ios::inRead mode (default for ifstream)
ios::appAppend to end of file
ios::truncTruncate file (default for ofstream)
ios::binaryOpen in binary mode

Appending to a File

std::ofstream log("log.txt", std::ios::app);
log << "New entry" << std::endl;
// Each run adds a line instead of overwriting the file

Checking File Status

std::ifstream inFile("file.txt");
if (!inFile) {
    std::cerr << "Error opening file!";
    return 1;
}

Best Practices

  • Always check if file opened successfully
  • Use getline for text files
  • Prefer letting the fstream destructor close the file (RAII)

Always check if a file opened successfully before reading or writing. Use is_open() or the ! operator to verify.

Common mistakes: using a stream that failed to open silently does nothing - always check is_open() or the ! operator first, and forgetting that ofstream overwrites by default unless you open with std::ios::app.

Key takeaway: Use ifstream for reading, ofstream for writing, and always verify the file opened before use.

Try it: Write three lines to notes.txt, then read them back and print each line prefixed with its line number.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects