我正在为我的项目使用一个库。该库有时会向stdout打印一些消息。这对我来说是个问题,因为消息与应用程序消息混合在一起。停止此行为或将其打印到其他窗口将很有用。我正在使用C语言和Mingw32环境。我怎样才能做到这一点?谢谢。
答案 0 :(得分:0)
您也许可以(非必要地)将stdout
与其他流交换:
#include <stdio.h>
FILE *devnull;
#define SWAPSTDOUT() do{ FILE *tmp = stdout; stdout = devnull; devnull = tmp; }while(0)
int main(void)
{
/*program initialization*/
if(0==(devnull= fopen("/dev/null", "r"))) return 1;
fputs("your code 0\n",stdout);
SWAPSTDOUT();
fputs("library code 0\n",stdout); //should be silent
SWAPSTDOUT();
fputs("your code 1\n", stdout);
}
不幸的是,这不太可能与对stdout
进行硬编码的函数(例如printf
或puts
)一起使用。
如果您使用的是POSIX平台,则可能有freopen
,但是如果您无法保存原始流,那将无济于事。但是,在POSIX上,您可以fflush(stdout)
然后重新整理基础文件描述符,这应该非常可靠:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int devnull, tmp;
int swapstdout(void);
int main(void)
{
/*program initialization*/
if(0>(devnull=open("/dev/null", O_RDONLY))) return EXIT_FAILURE;
if(0>(tmp=dup(devnull))) return EXIT_FAILURE; //reserve a fd spot
fputs("your code 0\n",stdout);
if(0>swapstdout()) return EXIT_FAILURE:
fputs("library code 0\n",stdout); //should be silent
if(0>swapstdout()) return EXIT_FAILURE:
fputs("your code 1\n", stdout);
}
int swapstdout(void)
{
if(0>fflush(stdout)) return -1;
if(0>dup2(STDOUT_FILENO,tmp)) return -1; /*really shouldn't happen*/
if(0>dup2(devnull,STDOUT_FILENO)) return -1; /*really shouldn't happen*/
if(0>tmp=dup(devnull)) return -1; /*really shouldn't happen unless we're multithreaded and another thread steals the fd spot*/
}
这两种解决方案都取决于您的代码是单线程的。
无论如何,除非您明确要求它们对此类文件执行某些操作,否则表现良好的库函数应将它们不属于自己的文件留空。