Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Wednesday, August 21, 2024

C++ program to show working of read/write operation on multiple files.

 Objective: Write a C++ program to show working of read/write operation on multiple files.

Code:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    // Create objects for file streams

    ofstream outFile1, outFile2;  // Output file streams (writing to files)

    ifstream inFile1, inFile2;    // Input file streams (reading from files)

    // Open two files for writing

    outFile1.open("file1.txt");

    outFile2.open("file2.txt");

    if (!outFile1 || !outFile2) {

        cout << "Error opening files for writing!" << endl;

        return 1;

    }

    // Write some data to the files

    outFile1 << "This is the first file." << endl;

    outFile1 << "It contains data for demonstration." << endl;

    outFile2 << "This is the second file." << endl;

    outFile2 << "It also contains data for demonstration." << endl;

    // Close the output files

    outFile1.close();

    outFile2.close();

    // Open the same files for reading

    inFile1.open("file1.txt");

    inFile2.open("file2.txt");

    if (!inFile1 || !inFile2) {

        cout << "Error opening files for reading!" << endl;

        return 1;

    }

    // Read and display content from the first file

    cout << "Reading from file1.txt:" << endl;

    string line;

    while (getline(inFile1, line)) {

        cout << line << endl;

    cout << endl;

    // Read and display content from the second file

    cout << "Reading from file2.txt:" << endl;

    while (getline(inFile2, line)) {

        cout << line << endl;

   // Close the input files

    inFile1.close();

    inFile2.close();

    return 0;

}


Output:






No comments:

Post a Comment