Suppose I’ve got code like
#include <iostream>
using namespace std;
int main() {
cout << "Redirect to file1" << endl;
cout << "Redirect to file2" << endl;
return 0;
}
I want to redirect the first output to file1 and the second to file2. Is that possible?
I think in C, fclose(stdout) and reopen the stdout might help but I’m not sure how to reopen it or whether it works.
Thanks
UPDATE: What for?
I have a program A, which reads input from the user and generates corresponding output. Now I want to check whether it is correct, I have a program B which generate input for A, as well as correct output. B will generate one set of test data at a time. And I will have thousands of tests.
On my machine, a thousand times ./B > ``mktemp a.XXX`` works better than using ofstream. Using fstream for thousands of times, my hard drive light flashes crazily. But not when redirecting to temp file.
UPDATE2:
In C++, it seems that the prevailing answer is cout along with cerr.
What about C, apart from stderr, can I close stdout and reopen it?
You can always use the standard error stream for e.g. error messages.
For example, using the Windows [cmd.exe] command interpreter, and the Visual C++
clcompiler:[D:\dev\test] > type con >streams.cpp #include <iostream> using namespace std; int main() { cout << "Redirect to file1" << endl; cerr << "Redirect to file2" << endl; } ^Z [D:\dev\test] > cl streams.cpp streams.cpp [D:\dev\test] > streams 1>a.txt 2>b.txt [D:\dev\test] > type a.txt Redirect to file1 [D:\dev\test] > type b.txt Redirect to file2 [D:\dev\test] > _EDIT: added colorized code and boldface emphasis.