如何将流(FILE *)与stdout相关联?

时间:2012-06-23 09:08:27

标签: c io stream

现在每个模块都写入stderr,因此我无法关闭单个模块的输出。有谁知道我如何将流与stdout关联,因此每个模块将写入独立流,所以我可以将其关闭。例如:

fprintf(newStdout, "hello");

newStdout正在写入屏幕。我不知道如何将newStdout与屏幕关联起来。

2 个答案:

答案 0 :(得分:4)

来自http://www.cplusplus.com/reference/clibrary/cstdio/freopen/ - 它是C ++参考,但应该对C有效。

include <stdio.h>

int main ()
{
  freopen ("myfile.txt","w",stdout);
  printf ("This sentence is redirected to a file.");
  fclose (stdout);
  return 0;
}

我不认为你可以在每个模块的基础上这样做,因为stdoutstderr是全局变量。

答案 1 :(得分:1)

如果您的目标是让newStdout在某些时候表现得像stdout并且在某些时候保持沉默,那么您可以这样做:

// 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 );
}
相关问题