File I/O
Writing Files
Write text or binary data using std::ofstream, specify opening modes, and optimize write buffering.
Interview: Stream write modes, raw binary serialization, buffer management, and performance differences between std::endl and '\n'.
C++ uses std::ofstream (output file stream) to write data to files. Managing open modes (like append or binary) and controlling stream buffering are crucial for writing high-performance C++ code.
std::ofstream
A stream class specialized for writing files, supporting formatting operations via the << operator.
Open Modes
Combine modes like std::ios::app (append), std::ios::trunc (overwrite), and std::ios::binary.
Buffer Flushing
Understand when the stream buffer flushes to disk. Minimize explicit flushes to maximize I/O performance.
std::endl vs. '\n'
In loop-heavy file operations, developers often use std::endl to write newlines. However, std::endl does two things:
- Writes a newline character (
' ') to the stream. - Forcibly flushes the stream's internal buffer to the disk.
Explicitly flushing the buffer on every line bypasses the OS buffering layer, resulting in expensive system calls. Using '
' writes the newline and lets the stream buffer handle flushes automatically, improving performance by up to 10x.
Code Walkthrough
Demonstrates writing a text log in append mode and writing raw binary data.
#include <iostream> #include <fstream>void writeLog(const std::string& logMessage) { // Open in append mode (std::ios::app) std::ofstream logFile("app.log", std::ios::out | std::ios::app);
if (logFile.is_open()) { logFile << "[INFO] " << logMessage << '\n'; // Fast: no force-flush } }
void writeBinaryData() { int data[5] = {10, 20, 30, 40, 50};
// Open in binary mode (std::ios::binary) std::ofstream outFile("data.bin", std::ios::out | std::ios::binary);
if (outFile.is_open()) { // Cast array to char* and specify size in bytes outFile.write(reinterpret_cast<const char*>(data), sizeof(data)); } }
int main() { writeLog("Application started."); writeBinaryData(); return 0; }
Interview-Relevant Information
Q: Why is binary file output (ofstream::write) more efficient than text output?
Answer: Text output formats raw memory variables into string representations (e.g. converting the int 12345 to five ASCII characters). Binary output writes the raw memory bytes directly to disk without parsing or translation, which is faster and consumes less space.
Q: How do you append text to an existing file instead of overwriting it?
Answer: Specify the open mode std::ios::app. This moves the write pointer to the end of the file before every write operation. By default, std::ofstream uses std::ios::trunc, which deletes the file's existing content.
Quick Checklist
Did you use '
' instead of std::endl in loops? Did you open binary files with std::ios::binary? If yes, your file writing logic is optimal.
Use Cases
Saving application diagnostic events or execution logs to a persistent file.
Serializing internal structural state or savefiles in game development using binary formats.
Common Mistakes
Using std::endl inside high-frequency write loops, which forces disk flushes and degrades performance.
Writing numeric types to a binary file using the standard formatting operator << instead of stream::write.