Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Write to File in C++

Write to a text file in C++ with ofstream: open or create data.txt, check is_open, write lines and numbers with <<, and close. Learn what truncation does.

BeginnerFile Handling ProgramsExample 1 of 6
write-to-file.cpp
1#include <iostream>
2#include <fstream>
3using namespace std;
4
5int main() {
6 // Create and open file for writing
7 ofstream outFile("data.txt");
8
9 if (outFile.is_open()) {
10 // Write data to file
11 outFile << "Hello, World!" << endl;
12 outFile << "This is a C++ file handling program." << endl;
13 outFile << "Line 3: Learning file operations." << endl;
14
15 // Write numbers
16 outFile << 100 << " " << 200 << " " << 300 << endl;
17
18 outFile.close();
19 cout << "Data written to file successfully!" << endl;
20 } else {
21 cout << "Error: Unable to open file for writing." << endl;
22 }
23
24 return 0;
25}

Sample Output

Data written to file successfully!

is_open() was true and all writes finished.

In this one

  • How to open a file for writing with ofstream
  • Why you must check is_open()
  • That the default mode erases existing contents
  • Where the file is created

How it works

  1. 1

    Create ofstream outFile("data.txt").

  2. 2

    Check is_open().

  3. 3

    Write three lines and a line of numbers with <<.

  4. 4

    close() to flush and release the file.

  5. 5

    Print a success message.

Edge cases

Folder does not exist

Use ofstream f("missing/data.txt");

Opening fails and is_open() is false, so the error branch prints. ofstream creates files, not folders.

Running twice

Run the program again.

The file is truncated and rewritten, so it still has four lines, not eight. Use ios::app to keep old content.

What's going on

Writing to a file in C++ looks almost exactly like printing with cout. You open an ofstream (output file stream) and then use << on it.

ofstream outFile("data.txt"); opens data.txt for writing. If the file does not exist, it is created. If it does exist, its old contents are erased first, because the default mode truncates. The file is created in the program's current working directory, which is usually the folder you run it from, not necessarily the folder holding the source code.

outFile.is_open() checks that opening worked. It can fail when the folder is read-only, the disk is full, or the path points to a folder that does not exist. Writing to a stream that failed to open does nothing, silently, so this check matters.

The four << lines write three text lines and one line of numbers. Numbers are converted to text, so 100 is stored as the characters 1, 0, 0, not as a binary int.

outFile.close() flushes anything still in the buffer and releases the file. The ofstream destructor would close it anyway at the end of the block, but closing explicitly makes the point at which the data is safely on disk clear.

The program prints only the success message. To see what was written, open data.txt in an editor or run the file-read program next. The file then contains:

Hello, World!

This is a C++ file handling program.

Line 3: Learning file operations.

100 200 300

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <fstream> is there because it provides file stream classes (ofstream, ifstream). Leave one out and the compiler stops at the first name it does not recognize.

Understanding File Writing

ofstream Concept:

Output file stream
Used for writing to files
Similar to cout but writes to file
Creates file if doesn't exist

File Modes:

Default: overwrites existing file
ios::app: append mode (adds to end)
ios::binary: binary mode

Opening File for Writing

Creating ofstream:

ofstream outFile("data.txt");

What happens here:

Creates ofstream object
Opens file "data.txt" for writing
Creates file if doesn't exist
Overwrites if file exists

Checking Success:

if (outFile.is_open()) {

// File opened successfully

}

Writing to File

Using << Operator:

outFile << "Hello, World!" << endl;

outFile << 100 << " " << 200 << endl;

What happens here:

<< operator works like cout
Writes text, numbers, variables
endl adds newline
Data written sequentially

Closing File

Using close():

outFile.close();

What happens here:

Closes file stream
Flushes any buffered data
Releases file resource
Good practice to always close

When to Use File Writing

Good fits:

Saving program output
Data logging
Configuration files
Persistent data storage
Report generation

Example Scenarios:

Saving user data
Logging events
Exporting results
Creating reports
Data backup

Important Considerations

File Overwriting:

Default mode overwrites existing file
Use ios::app to append instead
Be careful not to lose data
Check if file exists if needed

Error Handling:

Always check is_open()
Handle file open failures
Check write permissions
Handle disk space issues

File Paths:

Relative path: "data.txt" (current directory)
Absolute path: "/path/to/file.txt"
Use forward slashes (/) or double backslashes (\)

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What happens to an existing data.txt when this program runs?

Pick an answer to check it.

Question 2

Why check is_open()?

Pick an answer to check it.

Questions people ask

Where is data.txt saved?

In the current working directory. IDEs often set this to a build folder.

Is endl needed?

"\n" is enough. endl also flushes, which is slower when writing many lines.

How do I write to a different folder?

Pass a full or relative path such as "out/data.txt", and make sure the folder exists.