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.
1#include <iostream>2#include <fstream>3using namespace std;45int main() {6 // Create and open file for writing7 ofstream outFile("data.txt");89 if (outFile.is_open()) {10 // Write data to file11 outFile << "Hello, World!" << endl;12 outFile << "This is a C++ file handling program." << endl;13 outFile << "Line 3: Learning file operations." << endl;1415 // Write numbers16 outFile << 100 << " " << 200 << " " << 300 << endl;1718 outFile.close();19 cout << "Data written to file successfully!" << endl;20 } else {21 cout << "Error: Unable to open file for writing." << endl;22 }2324 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
Create ofstream outFile("data.txt").
- 2
Check is_open().
- 3
Write three lines and a line of numbers with <<.
- 4
close() to flush and release the file.
- 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:
File Modes:
Opening File for Writing
Creating ofstream:
ofstream outFile("data.txt");
What happens here:
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:
Closing File
Using close():
outFile.close();
What happens here:
When to Use File Writing
Good fits:
Example Scenarios:
Important Considerations
File Overwriting:
Error Handling:
File Paths:
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.