When programming with c-style i/o I sometimes use freopen() to reopen stdin for testing purposes so that I don't have to retype the input over and over. I was wondering if there is an equivalent for c++ i/o streams. Also, I know that I can use pipes to redirect it on the command line/terminal/whateveritis but I was wondering if there was a way to do it inside my code (because as you can see, I'm not very knowledgeable about the cl/t/w).
The freopen() function closes the file that is currently associated with stream and reassigns stream to the file that is specified by filename. The freopen() function opens the new file associated with stream with the given mode, which is a character string specifying the type of access requested for the file.
Standard Input Stream (cin) in C++ It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file.
freopen
also works with cin
and cout
. No need to search for something new.
freopen("input.txt", "r", stdin); // redirects standard input freopen("output.txt", "w", stdout); // redirects standard output int x; cin >> x; // reads from input.txt cout << x << endl; // writes to output.txt
Edit: From C++ standard 27.3.1:
The object cin controls input from a stream buffer associated with the object stdin, declared in
<cstdio>
.
So according to the standard, if we redirect stdin
it will also redirect cin
. Vice versa for cout
.
#include <iostream> #include <fstream> int main() { // Read one line from stdin std::string line; std::getline(std::cin, line); std::cout << line << "\n"; // Read a line from /etc/issue std::ifstream issue("/etc/issue"); std::streambuf* issue_buf = issue.rdbuf(); std::streambuf* cin_buf = std::cin.rdbuf(issue_buf); std::getline(std::cin, line); std::cout << line << "\n"; // Restore sanity and read a line from stdin std::cin.rdbuf(cin_buf); std::getline(std::cin, line); std::cout << line << "\n"; }
http://www.cplusplus.com/reference/iostream/ios/rdbuf/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With