mihajlv
mihajlv

Reputation: 2315

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

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.

Upvotes: 4

Views: 14277

Answers (2)

Michael Anderson
Michael Anderson

Reputation: 73520

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 );
}

Upvotes: 3

Michael Anderson
Michael Anderson

Reputation: 73520

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.

Upvotes: 4

Related Questions