0
0
CppHow-ToBeginner · 3 min read

How to Use ofstream in C++ for File Writing

Use std::ofstream in C++ to create and write to files by opening a file stream and using the insertion operator <<. Always check if the file opened successfully before writing and close the stream when done.
📐

Syntax

The basic syntax to use ofstream is:

  • std::ofstream file; declares a file output stream.
  • file.open("filename.txt"); opens the file for writing.
  • file << "text"; writes text to the file.
  • file.close(); closes the file stream.

You can also open the file directly when declaring the ofstream object.

cpp
std::ofstream file;
file.open("example.txt");
file << "Hello, file!";
file.close();
💻

Example

This example shows how to create a file named output.txt and write a line of text into it. It also checks if the file opened successfully before writing.

cpp
#include <iostream>
#include <fstream>

int main() {
    std::ofstream file("output.txt");
    if (!file) {
        std::cerr << "Error opening file." << std::endl;
        return 1;
    }
    file << "This is a line written to the file." << std::endl;
    file.close();
    std::cout << "File written successfully." << std::endl;
    return 0;
}
Output
File written successfully.
⚠️

Common Pitfalls

Common mistakes when using ofstream include:

  • Not checking if the file opened successfully, which can cause silent failures.
  • Forgetting to close the file, which may cause data not to be saved properly.
  • Opening the file in the wrong mode (e.g., not using std::ios::app to append).

Always verify the file stream state and close the file when done.

cpp
#include <fstream>
#include <iostream>

int main() {
    std::ofstream file("data.txt");
    // Wrong: Not checking if file opened
    // file << "Hello" << std::endl; // This line should be commented out or removed to avoid writing without checking
    // Correct way:
    if (!file) {
        std::cerr << "Failed to open file." << std::endl;
        return 1;
    }
    file << "Hello" << std::endl;
    file.close();
    return 0;
}
📊

Quick Reference

Key points to remember when using ofstream:

  • Include <fstream> header.
  • Use std::ofstream to write files.
  • Open files with a filename or open() method.
  • Check if the file opened successfully with if(file) or if(!file).
  • Write using << operator.
  • Close files with close() or let destructor handle it.

Key Takeaways

Use std::ofstream to write data to files in C++.
Always check if the file opened successfully before writing.
Close the file stream to ensure data is saved properly.
Use the insertion operator << to write text to the file.
Include the <fstream> header to use ofstream.