我正在编写一个小的 c++ 应用程序来包装 opencv haar 训练函数(即 cvCreateTreeCascadeClassifier)。该函数向控制台抛出一整套输出,我希望解析此输出,以便我可以在我的代码中填充各种变量。
我希望使用的函数不是实际 openCV 库的一部分;相反,它必须作为项目的一部分使用我的代码构建。该函数的所有输出均通过 printf。
问题:是否可以在 printf 语句在控制台结束之前拦截它们?我已经设法使用 freopen 重定向它们,但这似乎有点笨拙,因为我需要解析文件,然后在函数调用完成后将其删除。此外,该函数可能会运行数小时(甚至可能数周!),因此如果文件不断被附加,文件的大小可能会成为一个问题。
要求:我需要这个应用程序是 c++ 并在 windows 和 linux 上运行(但如果需要的话,条件编译语句没有问题)。我还希望仍然能够在控制台上看到我的 cout 和 cerr 消息(只是看不到 printf)。
我的谷歌搜索让我失去了生存的意愿!任何人都可以通过代码示例或指向我应该寻找答案的地方的指针来帮助解决方案吗?
谢谢
最佳答案
你可以做的是:
- 创建管道
- 使管道的可写端成为新的标准输出
- 从管道的可读部分读取
读取和写入应该在不同的线程中进行,否则您的程序可能会在管道的一端饿死。
这是一个如何在 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;
}
这段代码应该打印出来
buf=>Hi there
(我在这里使用断言,因为我懒得为这个例子做真正的错误检查)
关于c++ - 如何将 printf 输出重定向回代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5911147/