C++ Files
Lesson outline
Introduction to File Handling
File handling in C++ is performed using the <fstream> library, which provides three main classes:
std::ofstream: For creating and writing to files.std::ifstream: For reading from files.std::fstream: For both reading and writing.
Common operations include creating, opening, reading, writing, appending, seeking, and closing. Streams automatically close when they go out of scope (RAII).
Writing to a File
Use std::ofstream to create and write to files. By default, opening an ofstream with just a filename uses ios::out | ios::trunc, which truncates (overwrites) the file if it exists. Use ios::app to append instead.
Reading from a File
Appending to a File
To append to an existing file, open it with the ios::app flag (append-only).
Seeking (Moving the Read/Write Position)
You can move the file position indicators to read/write at arbitrary locations:
seekp/tellpfor the output (put) positionseekg/tellgfor the input (get) position
Text vs Binary Mode
Open non-text data with ios::binary, especially on Windows where text mode may translate newlines:
- Text mode may translate
\nto\r\non write and back on read. - Binary mode performs no translation.
File Modes
| Flag | Description |
|---|---|
| ios::in | Open for reading |
| ios::out | Open for writing (implies truncation unless combined with ios::app or paired with ios::in/ios::ate) |
| ios::app | Append on every write (seek to end before each write) |
| ios::trunc | Truncate file to zero length on open (if it exists) |
| ios::binary | Open in binary mode (no text translation) |
| ios::ate | Open and seek to end immediately (not append-only; you can still seek elsewhere) |
Error Handling & Exceptions
Check stream state after operations (if (!stream)) or enable exceptions for critical I/O:
Set exceptions and handle failures with try/catch:
Best Practices
- Rely on RAII: streams close automatically when they go out of scope; call
close()early only if you need to reopen or to check close errors explicitly. - Prefer
'\n'overstd::endlunless you need to flush. - Choose modes deliberately:
ofstreamalone truncates; useios::appto append or pairios::outwithios::in/ios::ateto avoid truncation. - Use
ios::binaryfor non-text data. - Always verify operations succeeded (check stream state or use exceptions).