0Pricing
C++ Academy · Lesson

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

  1. Reading Files with ifstream
  2. Writing Files with ofstream
  3. Binary File I/O
  4. Error Handling and State
← Back to C++ Academy