0
0
C++programming~5 mins

File output using ofstream in C++

Choose your learning style9 modes available
Introduction

We use ofstream to save data from a program into a file on your computer. This helps keep information even after the program stops.

Saving user settings so they load next time the program runs.
Writing a report or log of what the program did.
Storing game scores or progress to continue later.
Exporting data for use in other programs or sharing.
Syntax
C++
#include <fstream>
std::ofstream outputFile("filename.txt");
outputFile << "Text to write";
outputFile.close();

Always include #include <fstream> to use ofstream.

Remember to close the file with close() to save changes properly.

Examples
This writes "Hello, file!" into a file named example.txt.
C++
#include <fstream>

int main() {
    std::ofstream file("example.txt");
    file << "Hello, file!";
    file.close();
    return 0;
}
Shows how to open a file separately and write numbers separated by space.
C++
#include <fstream>

int main() {
    std::ofstream file;
    file.open("data.txt");
    file << 123 << " " << 456;
    file.close();
    return 0;
}
Sample Program

This program creates a file called output.txt and writes two lines of text into it. It also checks if the file opened correctly and tells the user when done.

C++
#include <fstream>
#include <iostream>

int main() {
    std::ofstream outputFile("output.txt");
    if (!outputFile) {
        std::cout << "Error opening file." << std::endl;
        return 1;
    }
    outputFile << "Line 1: Hello, file output!\n";
    outputFile << "Line 2: Writing more text.";
    outputFile.close();
    std::cout << "Data written to output.txt" << std::endl;
    return 0;
}
OutputSuccess
Important Notes

If the file already exists, ofstream will overwrite it by default.

Use std::ios::app mode if you want to add text without erasing existing content.

Summary

ofstream lets you save text or data to files from your program.

Always check if the file opened successfully before writing.

Close the file to make sure all data is saved properly.