C++ Academy · Lesson

Writing Files with ofstream

Write output files.

Lesson 2 of 413 steps

Writing Files with ofstream is a free C++ Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

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;
}

Truncation by Default

Opening an existing file with ofstream erases its previous contents. Each run starts fresh.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("t.txt") << "old content\n";
    std::ofstream out("t.txt");
    out << "new content\n";
    std::ifstream in("t.txt");
    std::string line; std::getline(in, line);
    std::cout << line << '\n';
    return 0;
}

Appending with app Mode

Pass std::ios::app to keep existing content and add new data at the end.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("log.txt") << "line1\n";
    std::ofstream out("log.txt", std::ios::app);
    out << "line2\n";
    out.close();
    std::ifstream in("log.txt");
    std::string l; int n = 0;
    while (std::getline(in, l)) ++n;
    std::cout << n << " lines\n";
    return 0;
}

Checking the Write Succeeded

Test the stream after opening. If it is in a bad state, writing will silently fail.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("ok.txt");
    if (!out) {
        std::cout << "failed to open\n";
        return 1;
    }
    out << "safe write\n";
    std::cout << "write ok\n";
    return 0;
}

Writing Numbers and Formatting

I/O manipulators like std::fixed and std::setprecision apply to file streams too.

#include <iostream>
#include <fstream>
#include <iomanip>

int main() {
    std::ofstream out("pi.txt");
    out << std::fixed << std::setprecision(3) << 3.14159 << '\n';
    out.close();
    std::ifstream in("pi.txt");
    std::string s; in >> s;
    std::cout << s << '\n';
    return 0;
}

Writing a Loop of Data

Write many lines by looping. Each iteration sends a record to the file.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("squares.txt");
    for (int i = 1; i <= 5; ++i) out << i << ' ' << i * i << '\n';
    out.close();
    std::cout << "wrote 5 rows\n";
    return 0;
}

Flushing the Buffer

Output is buffered. std::flush or std::endl forces the buffer to disk immediately; closing also flushes.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("flush.txt");
    out << "important" << std::flush;
    std::cout << "flushed to disk\n";
    return 0;
}

endl vs newline

'\n' just adds a newline. std::endl adds a newline and flushes, which is slower in tight loops.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("nl.txt");
    out << "fast\n";          // newline only
    out << "slow" << std::endl; // newline + flush
    std::cout << "both written\n";
    return 0;
}

Round-Trip Write then Read

A common pattern: write data, close, then reopen to read it back.

#include <iostream>
#include <fstream>

int main() {
    {
        std::ofstream out("rt.txt");
        out << 7 << ' ' << 8 << '\n';
    }
    std::ifstream in("rt.txt");
    int a, b; in >> a >> b;
    std::cout << a + b << '\n';
    return 0;
}

Choosing Open Modes

Combine flags with |. Common modes: ios::out (default), ios::app (append), ios::trunc (erase).

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("modes.txt", std::ios::out | std::ios::trunc);
    out << "fresh\n";
    std::cout << "opened with explicit modes\n";
    return 0;
}

Quick Check

Test your understanding of ofstream modes.

Recap

You learned that std::ofstream:

  • writes with <<, truncating by default
  • appends with std::ios::app
  • buffers output; std::flush/std::endl/closing send it to disk

Next, you'll handle raw bytes with binary file I/O.

Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Writing Files with ofstream” lesson free?

Yes — any 3 lessons of the C++ Academy learning path, including “Writing Files with ofstream”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

What will I learn in “Writing Files with ofstream”?

Write output files. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Writing Files with ofstream” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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