如何将printf输出重定向回代码?

joh*_*ohn 9 c++ console printf redirect opencv

我正在编写一个小的c ++应用程序来包装opencv haar训练函数(即cvCreateTreeCascadeClassifier).该函数将整个输出加载到控制台,我希望解析此输出,以便我可以在我的代码中填充各种变量.

我想使用的函数不是实际的openCV库的一部分; 相反,它必须使用我的代码构建作为项目的一部分.函数的所有输出都是通过printf输出的.

问题:是否可以在最终出现在控制台上之前拦截printf语句?我已经设法使用freopen重定向它们,但这似乎有点笨拙,因为我需要解析文件然后在函数调用完成后删除它.此外,该功能可能会运行几个小时(甚至可能是几周!),因此如果文件的大小也经常被附加,那么文件的大小可能会成为问题.

要求:我需要这个应用程序是c ++并在Windows和Linux上运行(但如果需要,条件编译语句没有问题).我还希望能够在控制台上看到我的cout和cerr消息(只是不是printf).

我的谷歌搜索已经取消了我的生活意愿!任何人都可以通过代码示例或指向我应该寻找答案的地方的指针帮助解决方案吗?

谢谢

Nor*_*ame 7

你能做的是:

  • 创建一个管道
  • 使管道的可写端成为新的标准输出
  • 从管道的可读部分读取

读写应该在不同的线程中发生,否则你的程序会在管道的一端挨饿.

以下是如何在unix和windows中进行重定向的示例:


#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
/* gcc defined unix */
#ifdef unix
#include <unistd.h>
#endif
#ifdef WIN32
#include <io.h>
#define pipe(X) _pipe(X,4096,O_BINARY)     
#define fileno _fileno
#define dup2 _dup2
#define read _read

#endif
#include <assert.h>

int main()
{
    int fds[2]; 
    int res; 
    char buf[256];
    int so; 

    res=pipe(fds);
    assert(res==0); 

    so=fileno(stdout);
    // close stdout handle and make the writable part of fds the new stdout.
    res=dup2(fds[1],so);
    assert(res!=-1); 

    printf("Hi there\n");
    fflush(stdout);
    // reading should happen in a different thread

    res=read(fds[0],buf,sizeof(buf)-1);
    assert(res>=0 && res<sizeof(buf));
    buf[res]=0;
    fprintf(stderr,"buf=>%s\n",buf);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

此代码应该打印

buf=>Hi there
Run Code Online (Sandbox Code Playgroud)

(我在这里使用assert,因为我懒得为这个例子做真正的错误检查)