File Handling
intermediateWhat 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.
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.
Writing to a File
Reading from a File
Reading Numbers
File Modes
| Mode | Description |
|---|---|
| ios::out | Write mode (default for ofstream) |
| ios::in | Read mode (default for ifstream) |
| ios::app | Append to end of file |
| ios::trunc | Truncate file (default for ofstream) |
| ios::binary | Open in binary mode |
Appending to a File
Checking File Status
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.