Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I associate a stream (FILE *) with stdout?

Tags:

c

io

stream

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.

like image 867
mihajlv Avatar asked Sep 02 '25 14:09

mihajlv


1 Answers

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 );
}
like image 125
Michael Anderson Avatar answered Sep 05 '25 08:09

Michael Anderson