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());
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());
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);
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!