std::ofstream
- C++ course
- Intermediate
- Lesson 89/116
- 5 min
Learn to write files with std::ofstream.
Writing with std::ofstream
std::ofstream opens a file for writing. You send data to the file with the << operator. If the file does not exist it is created; if it exists its content is erased and overwritten.
Example: std::ofstream out("data.txt"); out << "Hi"; out.close();. These three lines create data.txt, write Hi into it and close it. After writing you can read the file back with std::ifstream to verify the content. Calling close() when done is a good habit; it flushes the buffer to disk.
Writing multiple values
You can write several values in a single << chain. out << "Name: " << name << " " << age; writes a string, a variable and a number in sequence.
To separate lines use \n or std::endl. Example: out << "First" << std::endl << "Second"; writes two lines. Numbers need no extra work: out << 42; writes 42 directly. Data written to a file can later be read back with >>; the format is preserved.
Practice Write to a file and read it back
The starting code reads the file and prints it. Open data.txt with std::ofstream, write "Hi" into it and close it. The reading part is ready; it will read from the file you wrote.
Starter code
#include <iostream>
#include <fstream>
#include <string>
int main() {
// Write "Hi" to the file with std::ofstream
// Read the file and print
std::ifstream in("data.txt");
std::string word;
in >> word;
std::cout << word;
return 0;
}Sample solution
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream out("data.txt");
out << "Hi";
out.close();
std::ifstream in("data.txt");
std::string word;
in >> word;
std::cout << word;
return 0;
}Expected output
Hi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write to the file
out << ____;
out << "Hi";
Explanation: A string is written in double quotes.
2 What happens if the file opened with std::ofstream already exists?
std::ofstream out("data.txt");- Content is appended
- An error is thrown
- Content is erased and overwritten Correct answer
- It opens read-only
Explanation: ofstream erases and overwrites by default.
3 Match each piece to its role
| Term | Meaning |
|---|---|
std::ofstream |
File writing |
<< |
Data writing |
out.close() |
Closing the file |
std::endl |
Line ending |