Home C++ Tutorial C++ program to write characters onto a file and read characters from a file

C++ program to write characters onto a file and read characters from a file

by Anup Maurya
1 minutes read

C++ program that demonstrates how to write characters onto a file and read characters from a file.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    // Writing characters onto a file
    ofstream outputFile("example.txt");

    if (outputFile.is_open()) {
        outputFile << "Hello World!" << endl;
        outputFile << "This is a sample file." << endl;
        outputFile.close();
        cout << "Characters written to file successfully." << endl;
    }
    else {
        cout << "Unable to open file for writing." << endl;
        return 1;
    }

    // Reading characters from a file
    ifstream inputFile("example.txt");

    if (inputFile.is_open()) {
        char ch;
        while (inputFile.get(ch)) {
            cout << ch;
        }
        inputFile.close();
        cout << endl << "Characters read from file successfully." << endl;
    }
    else {
        cout << "Unable to open file for reading." << endl;
        return 1;
    }

    return 0;
}

related posts

Leave a Comment

Enable Notifications OK No thanks