Home > Backend Development > C++ > How to Redirect C Standard Input and Output to External Files?

How to Redirect C Standard Input and Output to External Files?

DDD
Release: 2024-12-19 00:03:10
Original
473 people have browsed it

How to Redirect C   Standard Input and Output to External Files?

Redirecting Input and Output to External Files

Redirecting input from standard input (cin) and output from standard output (cout) to external files is a useful technique for testing, debugging, or analyzing program behavior.

To redirect cin to a specified file (e.g., in.txt):

  • Open an ifstream object for the input file.
  • Save the old buffer associated with cin using cin.rdbuf().
  • Redirect cin to the input file's buffer using cin.rdbuf(in.rdbuf()).

To redirect cout to a specified file (e.g., out.txt):

  • Follow the same steps as for redirecting cin, but use ofstream object and cout.rdbuf() instead.

Example Code:

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

int main() {
    // Redirect cin to in.txt
    std::ifstream in("in.txt");
    std::streambuf *cinbuf = std::cin.rdbuf();
    std::cin.rdbuf(in.rdbuf());

    // Redirect cout to out.txt
    std::ofstream out("out.txt");
    std::streambuf *coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    // Read and write to the redirected streams
    std::string line;
    while (std::getline(std::cin, line)) {
        std::cout << line << "\n";
    }

    // Reset to standard input and output
    std::cin.rdbuf(cinbuf);
    std::cout.rdbuf(coutbuf);
}
Copy after login

Note: You can also redirect both input and output in a single line using the following syntax:

auto cinbuf = std::cin.rdbuf(in.rdbuf());
auto coutbuf = std::cout.rdbuf(out.rdbuf());
Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template