![](/img/trans.png)
[英]How redirect std::ostream to a file or /dev/null in c++ and linux
[英]redirect std output of a c function to null
我有一個C函數可以生成輸出,大概使用了printf或類似的函數。 如何重定向輸出,以便在執行該函數時不會生成該輸出,然后再將其還原? 像下面這樣。
int main()
{
// disable output
c_function(); // generates output
// enable output
return 0
}
如果您不能更改函數本身(例如,通過提供其他輸出文件描述符),則此方法應該起作用:
int outfd;
int savefd;
fflush( stdout ); // make sure everything is written to 1
savefd = dup( 1 ); // dup stdout for restore
outfd = creat( "mystdout.txt", 0666 ); // create an output file
dup2( outfd, 1 ); // dup that fd to stdout
functionWithPrintf( );
fflush( stdout ); // make sure everything is written to 1
close( outfd );;
dup2( savefd, 1 );
printf( "Back again\n" );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.