C++ Beginner

cpp_019: Writing to Files with ofstream in C++

codeaddict 2025. 4. 5. 19:57

When you need to save data from your C++ program to a file, ofstream (output file stream) is what you'll use. It's part of the <fstream> library and works similarly to writing to the console with cout, but instead sends data to a file.

Basic Syntax

First, you need to include the right header:

#include <fstream>

Creating and using an ofstream has three main steps:

  1. Create an ofstream object and open a file
  2. Check if the file opened successfully
  3. Write data to the file
  4. Close the file (automatically happens when the object is destroyed, but good to do explicitly)
#include <fstream> // Include this to use ofstream

std::ofstream file;              // Create an ofstream object
file.open("filename.txt");       // Open a file (creates it if it doesn’t exist)
file << "Stuff to write";        // Write to the file
file.close();
  • #include <fstream>: Brings in the file-handling tools.
  • std::ofstream file;: Makes an object called file (name it whatever you want).
  • file.open(“filename.txt”): Opens (or creates) the file in the same folder as your program.
  • file << “text”: Uses the << operator (like cout) to write.
  • file.close(): Shuts the file to save changes and free resources.

You can also combine opening and creating in one line:

std::ofstream file("filename.txt");

Example 1: Writing a Simple Message

Let’s start basic — writing a line to a file.

#include <fstream>
#include <string>

int main() {
    std::ofstream file("message.txt");
    file << "Hello from C++!\n"; // \n adds a newline
    file.close();
    return 0;
}

What Happens:

  • Creates (or overwrites) message.txt in your program’s folder.
  • Writes “Hello from C++!” to it.
  • Closes the file.

Key Parts:

  • std::ofstream file(“message.txt”): Opens the file right away.
  • file <<: Sends the text to the file, just like cout.
  • file.close(): Saves and finishes up.

Check message.txt after running — it’ll have your message!

Example 2: Saving User Input

Now, let’s save something the user types.

#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ofstream file("note.txt");
    std::string userInput;
    
    std::cout << "Type a note: ";
    std::getline(std::cin, userInput); // Get a full line
    
    file << "Note: " << userInput << "\n";
    file.close();
    
    std::cout << "Saved to note.txt!\n";
    return 0;
}

What Happens:

  • Asks for input (e.g., “Buy milk”).
  • Writes “Note: Buy milk” to note.txt.
  • Tells you it’s saved.

Key Parts:

  • std::getline(std::cin, userInput): Grabs a whole line (spaces included), unlike cin >>.
  • file << “Note: “ << userInput: Chains text and the variable together.
  • File gets created/overwritten in your program’s directory.

Run it, type something, and check note.txt.