Write to File

Writing Data to a File in C++

BeginnerTopic: File Handling Programs
Back

C++ Write to File Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    // Create and open file for writing
    ofstream outFile("data.txt");
    
    if (outFile.is_open()) {
        // Write data to file
        outFile << "Hello, World!" << endl;
        outFile << "This is a C++ file handling program." << endl;
        outFile << "Line 3: Learning file operations." << endl;
        
        // Write numbers
        outFile << 100 << " " << 200 << " " << 300 << endl;
        
        outFile.close();
        cout << "Data written to file successfully!" << endl;
    } else {
        cout << "Error: Unable to open file for writing." << endl;
    }
    
    return 0;
}
Output
Data written to file successfully!

Understanding Write to File

Writing to a file uses ofstream (output file stream). Open file with ofstream, check if open() succeeded, write using << operator (same as cout), and close() when done. The file is created if it doesn't exist, or overwritten if it exists. Always check if file opened successfully before writing.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents