Simultaneously Redirecting Input and Output to Files
One may desire to redirect the standard input and output streams to files for diverse reasons, such as collecting user data or performing batch processing. This article provides a comprehensive solution for achieving this in C .
Solution
The provided C code effectively demonstrates how to redirect the standard input (cin) to a designated file ("in.txt") and the standard output (cout) to a specified file ("out.txt"):
#include <iostream> #include <fstream> #include <string> void f() { std::string line; while (std::getline(std::cin, line)) { // input from "in.txt" std::cout << line << "\n"; // output to "out.txt" } } int main() { std::ifstream in("in.txt"); std::streambuf *cinbuf = std::cin.rdbuf(); // save old cin buffer std::cin.rdbuf(in.rdbuf()); // redirect std::cin to "in.txt" std::ofstream out("out.txt"); std::streambuf *coutbuf = std::cout.rdbuf(); // save old cout buffer std::cout.rdbuf(out.rdbuf()); // redirect std::cout to "out.txt" std::string word; std::cin >> word; // input from "in.txt" std::cout << word << " "; // output to "out.txt" f(); // call function std::cin.rdbuf(cinbuf); // reset cin to standard input std::cout.rdbuf(coutbuf); // reset cout to standard output std::cin >> word; // input from standard input std::cout << word; // output to standard output }
To redirect both input and output in a single line:
auto cinbuf = std::cin.rdbuf(in.rdbuf()); // save and redirect input
This principle applies to any stream, allowing user input and program output to be managed conveniently.
The above is the detailed content of How Can I Redirect Both Standard Input and Output to Files in C ?. For more information, please follow other related articles on the PHP Chinese website!