问题
Right now each module is writing to stderr, thus I cannot turnoff output of an individual one. Does anyone know how I can associate a stream with stdout thus each module will write to independent stream so I can turn it off. For example:
fprintf(newStdout, "hello");
newStdout
is writing to the screen. I don't know how to associate newStdout
with the screen.
回答1:
If your aim is to just have newStdout
behave like stdout
some of the time and silence it some of the time, you can do something like this:
// Global Variables
FILE * newStdout;
FILE * devNull;
int main()
{
//Set up our global devNull variable
devNull = fopen("/dev/null", "w");
// This output will go to the console like usual
newStdout = stdout;
call_something_that_uses_newStdout();
//This will have no output
newStdout = devNull;
call_something_that_uses_newStdout();
//This will log to a file
newStdout = fopen("log.txt","w");
call_something_that_uses_newStdout();
fclose( newStdout ); // -- If we don't close it here we'll never be able to close it;)
//Clean up our global devNull
fclose( devNull );
}
回答2:
From http://www.cplusplus.com/reference/clibrary/cstdio/freopen/ - Its a C++ reference, but should be valid for C.
include <stdio.h>
int main ()
{
freopen ("myfile.txt","w",stdout);
printf ("This sentence is redirected to a file.");
fclose (stdout);
return 0;
}
I don't think you can do this on a per-module basis though, as stdout
and stderr
are global variables.
来源:https://stackoverflow.com/questions/11168244/how-can-i-associate-a-stream-file-with-stdout