Redirecting Input and Output Streams to Files
To redirect standard input (cin) and standard output (cout) to files for input and output operations, respectively, follow these steps:
Implementation:
#include <iostream> #include <fstream> #include <string> int main() { // Open the input and output files std::ifstream in("in.txt"); std::ofstream out("out.txt"); // Redirect cin and cout to the files std::streambuf* cinbuf = std::cin.rdbuf(); std::cin.rdbuf(in.rdbuf()); std::streambuf* coutbuf = std::cout.rdbuf(); std::cout.rdbuf(out.rdbuf()); // Perform input and output operations std::string line; while (std::getline(std::cin, line)) { std::cout << line << "\n"; } // Reset cin and cout to standard streams std::cin.rdbuf(cinbuf); std::cout.rdbuf(coutbuf); return 0; }
Explanation:
Simplified Redirection:
You can also save and redirect in one line using:
auto cinbuf = std::cin.rdbuf(in.rdbuf());
This sets cin's buffer to in.rdbuf() and returns the old buffer associated with cin. The same technique can be used with std::cout.
The above is the detailed content of How Can I Redirect C Standard Input and Output Streams to Files?. For more information, please follow other related articles on the PHP Chinese website!