Home > Backend Development > C++ > How Can I Redirect C 's `cin` and `cout` to External Files?

How Can I Redirect C 's `cin` and `cout` to External Files?

Patricia Arquette
Release: 2024-12-27 16:43:10
Original
400 people have browsed it

How Can I Redirect C  's `cin` and `cout` to External Files?

Redirecting cin and cout to External Files

To redirect the input and output streams (cin and cout, respectively) to external files, follow these steps:

#include <iostream>
#include <fstream>

int main() {
    // Open input file for reading
    std::ifstream in("in.txt");
    // Save old input buffer
    std::streambuf *cinbuf = std::cin.rdbuf();
    // Redirect cin to input file
    std::cin.rdbuf(in.rdbuf());

    // Open output file for writing
    std::ofstream out("out.txt");
    // Save old output buffer
    std::streambuf *coutbuf = std::cout.rdbuf();
    // Redirect cout to output file
    std::cout.rdbuf(out.rdbuf());
Copy after login

From this point onward, any input read from std::cin will come from "in.txt," and any output written to std::cout will be written to "out.txt."

To redirect in a single line, use:

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

This sets std::cin's buffer to in.rdbuf() and returns the old buffer for later use. The same technique can be used for std::cout (or any other stream).

Finally, to restore the standard input and output, reset the buffers:

std::cin.rdbuf(cinbuf);
std::cout.rdbuf(coutbuf);
Copy after login

The above is the detailed content of How Can I Redirect C 's `cin` and `cout` 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template