C ++:重定向STDOUT [英] C++: Redirecting STDOUT

查看:526
本文介绍了C ++:重定向STDOUT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我想重定向通常去到stdout流的输出到我定义的函数。我读到您可以将stdio重定向到某个文件,为什么不将该文件重定向到某个功能?

In my application, I want to redirect the output that would normally go to the stdout stream to a function I define. I read that you can redirect stdio to a file, so why not to a function?

例如:

void MyHandler( const char* data );

//<<Magical redirection code>>

printf( "test" );
std::cout << "test" << std::endl;

//MyHandler should have been called with "test" twice, at this point




  • 如何实现此类似行为?

  • 推荐答案

    p> @Konrad Rudolph是对的,你可以完全做到这一点,容易,至少cout / cerr / clog。你甚至不需要自己的streambuf实现,只需使用ostringstream。

    @Konrad Rudolph is right, you can totally do this, easily, at least for cout/cerr/clog. You don't even need your own streambuf implementation, just use an ostringstream.

    // Redirect cout.
    streambuf* oldCoutStreamBuf = cout.rdbuf();
    ostringstream strCout;
    cout.rdbuf( strCout.rdbuf() );
    
    // This goes to the string stream.
    cout << "Hello, World!" << endl;
    
    // Restore old cout.
    cout.rdbuf( oldCoutStreamBuf );
    
    // Will output our Hello World! from above.
    cout << strCout.str();
    

    同样的事情适用于cerr和clog,但在我的经验中,不适用于stdout / stderr一般,所以printf不会输出。 cout去stdout,但重定向cout不会重定向所有的stdout。至少,这是我的经验。

    Same thing works for cerr and clog, but in my experience that will NOT work for stdout/stderr in general, so printf won't output there. cout goes to stdout, but redirecting cout will not redirect all stdout. At least, that was my experience.

    如果数据量预计很小,freopen / setbuf的东西工作正常。我最后做的鸽友dup / dup2的东西重定向到管道。

    If the amount of data is expected to be small, the freopen/setbuf thing works fine. I ended up doing the fancier dup/dup2 thing redirecting to a pipe.

    更新:我写了一篇博客文章,显示我最后使用的dup2方法,您可以阅读此处。它是为OS X编写的,但可能在其他Unix风格中工作。我真的怀疑它会工作在Windows。同一事件的可可版本此处

    Update: I wrote a blog post showing the dup2 method I ended up using, which you can read here. It's written for OS X, but might work in other Unix flavors. I seriously doubt it would work in Windows. Cocoa version of the same thing here.

    这篇关于C ++:重定向STDOUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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