Write to File in C++

Writing Data to a File in C++.

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}

Output

Data written to file successfully!

What's going on

The program demonstrates file writing operations:

Creating and opening file for writing
Writing text and numbers to file
Checking if file opened successfully
Closing file after writing

File writing enables data persistence and output storage.

Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <fstream>
Provides file stream classes (ofstream, ifstream).

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");

How it works

:

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()) {

}

1// File opened successfully

Writing to File

Using << Operator

:

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

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

How it works

:

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

Closing File

Using close()

:

outFile.close();

How it works

:

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

When to Use File Writing

Best For

:

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;

This ends the program successfully.