如何将流(FILE *)与stdout关联? [英] How can I associate a stream (FILE *) with stdout?

查看:36
本文介绍了如何将流(FILE *)与stdout关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在每个模块都在写入stderr,因此我无法关闭单个模块的输出.有谁知道我如何将流与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 正在写入屏幕.我不知道如何将 newStdout 与屏幕关联.

newStdout is writing to the screen. I don't know how to associate newStdout with the screen.

推荐答案

如果您的目标是使 newStdout 在某些时候表现得像 stdout ,并使其保持沉默有时,您可以执行以下操作:

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

这篇关于如何将流(FILE *)与stdout关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆