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):
To redirect cout to a specified file (e.g., out.txt):
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); }
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());
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!