I have a method that prints lots of output, and sometimes it would be nice to redirect this to a file, rather than having it all on my terminal.
I found a way to "override" cout so that the output goes to a file, without having to change any cout to fprintf(). Also, please note that I can't simply do ./myProgram > file.txt, because I have an interactive menu-system I need to use, and I just don't want ALL output to the file.
The following (old) forum post shows how to do this;
http://www.thescripts.com/forum/thread133345.htmlHowever, I want to “modularize” this by placing the rdbuf() call in a separate method, like this:
CODE
void Graph::spawnWindow(char *filena) {
std::ostringstream call;
call << "emacs " << filena << " &";
system(call.str().c_str());
}
void Graph::coutToFile(char *filena) {
ofstream file;
file.open(filena);
cout << "\t\033[1mWriting to " << filena << "...\033[0m" << endl;
sbuf = cout.rdbuf(); // save current setting (in GLOBAL sbuf)
cout.rdbuf(file.rdbuf());
}
void Graph::resetCout() {
cout.rdbuf(sbuf); // reset (via GLOBAL sbuf)
}
This way I can simply invoke coutToFile(filename) from my menu (while the program is running), such that certain long loops are saved to file. Then I finish with resetCout() and spawnWindow(filename) to view the contents in a separate emacs window.
However, it seems the change to cout has a
scope limited to within the function that actually does the change/reroute cout.rdbuf(file.rdbuf()), so it does work if I copy the contents of coutToFile() into the method I want to “monitor”. However, I was hoping to make this a global change, so that also any submethods would also be rerouted to file...
Any tips?
Thanks for reading!