Programming Pandit

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


Latest Update

Sunday, November 17, 2024

Sequential Input and Output Operations in C++

 Sequential Input and Output Operations in C++

Sequential input and output operations in C++ involve processing data in a file in the order in which it is stored. These operations are straightforward and suited for applications where the data is read or written linearly.

C++ provides classes and functions for sequential I/O through the <fstream> library. The most commonly used classes are:

  • ifstream: For input (reading data from files).
  • ofstream: For output (writing data to files).
  • fstream: For both input and output operations.

Basic Workflow of Sequential I/O

  1. Input Operations:

    • Open a file for reading using ifstream.
    • Read data sequentially until the end of the file.
    • Close the file after reading.
  2. Output Operations:

    • Open a file for writing using ofstream.
    • Write data sequentially to the file.
    • Close the file after writing.

Example: Sequential Output Operation

Writing data sequentially to a file.




Example: Sequential Input Operation

Reading data sequentially from a file.


Program:


#include <iostream>

#include <fstream>

#include <string>

using namespace std;


int main() {

    ifstream infile("example.txt");

    if (!infile) {

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

        return 1;

    }

    string line;

    // Sequentially reading data from the file

    while (getline(infile, line)) {

        cout << line << endl; // Print each line

    }

    infile.close();

    return 0;

}






No comments:

Post a Comment