Home >Backend Development >C++ >How Can I Redirect C Standard Input and Output Streams to Files?

How Can I Redirect C Standard Input and Output Streams to Files?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 00:08:09458browse

How Can I Redirect C   Standard Input and Output Streams to Files?

Redirecting Input and Output Streams to Files

To redirect standard input (cin) and standard output (cout) to files for input and output operations, respectively, follow these steps:

Implementation:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    // Open the input and output files
    std::ifstream in("in.txt");
    std::ofstream out("out.txt");

    // Redirect cin and cout to the files
    std::streambuf* cinbuf = std::cin.rdbuf();
    std::cin.rdbuf(in.rdbuf());
    std::streambuf* coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    // Perform input and output operations
    std::string line;
    while (std::getline(std::cin, line)) {
        std::cout << line << "\n";
    }

    // Reset cin and cout to standard streams
    std::cin.rdbuf(cinbuf);
    std::cout.rdbuf(coutbuf);

    return 0;
}

Explanation:

  • Open the input and output files using std::ifstream and std::ofstream, respectively.
  • Save the current buffers of cin and cout using std::cin.rdbuf() and std::cout.rdbuf().
  • Redirect cin to the input file's buffer and cout to the output file's buffer using std::cin.rdbuf(in.rdbuf()) and std::cout.rdbuf(out.rdbuf()).
  • Perform input and output operations as usual.
  • Restore cin and cout to their original buffers using std::cin.rdbuf(cinbuf) and std::cout.rdbuf(coutbuf).

Simplified Redirection:

You can also save and redirect in one line using:

auto cinbuf = std::cin.rdbuf(in.rdbuf());

This sets cin's buffer to in.rdbuf() and returns the old buffer associated with cin. The same technique can be used with std::cout.

The above is the detailed content of How Can I Redirect C Standard Input and Output Streams to Files?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn