C++ ยท Chapter 41 of 49

C++ File Handling

The `<fstream>` header provides `ifstream` (input/reading), `ofstream` (output/writing), and `fstream` (both) for working with files. You open a file, perform reads/writes, then close it (or let the destructor close it automatically).

Always check whether a file opened successfully before using it, since a missing or locked file will cause the stream to enter a failed state silently.

Writing to a file

`std::ofstream out("data.txt"); out << "Hello"; out.close();` creates/overwrites data.txt with the given text.

Reading from a file

`std::ifstream in("data.txt"); std::string line; while (getline(in, line)) { ... }` reads the file line by line until the end.

Example 1 (cpp)
#include <fstream>
int main() {
    std::ofstream out("data.txt");
    out << "Hello, File!";
    out.close();
}
Output
(creates data.txt containing 'Hello, File!')

ofstream writes text into a new or existing file.

Example 2 (cpp)
std::ifstream in("data.txt");
std::string line;
getline(in, line);
std::cout << line;
Output
Hello, File!

ifstream reads the file's content back into a string.

Key points

  • <fstream> provides ifstream, ofstream, and fstream.
  • Always check if(file) or file.is_open() before use.
  • close() releases the file, though destructors do this too.
  • getline() reads a file line by line.
๐Ÿ’ก Note: Forgetting to check whether a file opened successfully is a common source of silent bugs in file-handling code.

๐Ÿ“ Quick Quiz

1. Which class is used to write to a file?

2. Which header provides file streams?

3. What should you check before using an opened file?