I have access to a third party library that does "good stuff." It issues status and progress messages to stdout. In a Console application I can see these messages just fine. In a Windows application they just go to the bit bucket.
Is there a fairly simple way to redirect stdout and stderr to a text control or other visible place. Ideally, this would not require any recompiles of the third party code. It would just intercept the steams at a low level. I'd like a solution where I just #include the header, call the initialization function and link the library as in...
#include "redirectStdFiles.h" void function(args...) { TextControl* text = new TextControl(args...); initializeRedirectLibrary(text, ...); printf("Message that will show up in the TextControl\n"); std::cout << "Another message that also shows up in TextControl\n"; }
Even better would be if it used some interface that I could override so it is not tied to any particular GUI library.
class StdFilesRedirector { public: writeStdout(std::string const& message) = 0; writeStderr(std::string const& errorMessage) = 0; readStdin(std::string &putReadStringHere) = 0; };
Am I just dreaming? Or does anyone know of something that can do something like this?
Edit after two answers: I think using freopen to redirect the files is a good first step. For a complete solution there would need to be a new thread created to read the file and display the output. For debugging, doing a 'tail -f' in a cygwin shell window would be enough. For a more polished application... Which is what I want to write... there would be some extra work to create the thread, etc.
The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.
Understanding the concept of redirections and file descriptors is very important when working on the command line. To redirect stderr and stdout , use the 2>&1 or &> constructs.
You need to create pipe (with CreatePipe()), then attach stdout to it's write end with SetStdHandle(), then you can read from pipe's read end with ReadFile() and put text you get from there anywhere you like.
You can redirect stdout, stderr and stdin using freopen.
From the above link:
/* freopen example: redirecting stdout */ #include <stdio.h> int main () { freopen ("myfile.txt","w",stdout); printf ("This sentence is redirected to a file."); fclose (stdout); return 0; }
You can also run your program via command prompt like so:
a.exe > stdout.txt 2> stderr.txt
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