Writing Files with ofstream
Write output files.
What Is ofstream?
std::ofstream (output file stream) writes data to files. It works like std::cout but its destination is a file.
#include <iostream>
#include <fstream>
int main() {
std::ofstream out("hello.txt");
out << "Hello, file!\n";
std::cout << "wrote file\n";
return 0;
}Writing Text
Use the << operator to write strings and numbers, exactly like printing to the console.
#include <iostream>
#include <fstream>
int main() {
std::ofstream out("report.txt");
out << "Score: " << 95 << '\n';
out << "Grade: A\n";
std::cout << "done\n";
return 0;
}All lessons in this course
- Reading Files with ifstream
- Writing Files with ofstream
- Binary File I/O
- Error Handling and State