如何将 printf 输出重定向回代码?
我正在编写一个 C++ 小应用程序来包装 opencv haar 训练函数(即 cvCreateTreeCascadeClassifier)。该函数向控制台抛出全部输出,我希望解析此输出,以便可以在代码中填充各种变量。
我希望使用的函数不是实际 openCV 库的一部分;相反,它必须作为项目的一部分使用我的代码构建。该函数的所有输出均通过 printf 进行。
问题:是否可以在 printf 语句最终到达控制台之前拦截它们?我已经设法使用 freopen 重定向它们,但这似乎有点笨拙,因为我需要解析文件,然后在函数调用完成时删除它。此外,该函数可能会运行几个小时(甚至可能是几周!),因此如果文件也不断被附加,则文件的大小可能会成为一个问题。
要求:我需要这个应用程序是 C++ 的,并且可以在 Windows 和 Linux 上运行(但如果需要的话,条件编译语句没有问题)。我还希望仍然能够在控制台上看到我的 cout 和 cerr 消息(只是不是 printf)。
我的谷歌搜索消除了我的生存意志!任何人都可以通过代码示例或指向我应该寻找答案的地方的指针来帮助解决方案吗?
谢谢
i'm writing a little c++ app to wrap around the opencv haar training function (namely cvCreateTreeCascadeClassifier). The function throws a whole load of output to the console and I wish to parse this output so that I can populate various variables in my code.
The function I wish to use is not part of the actual openCV library; instead it has to be built with my code as part of the project. All of the output from the the function is via printf.
Question: Is it possible to intercept the printf statements before they end up on the console? I've managed to redirect them using freopen but this seems a little clumsy as I then need to parse the file and then delete it when the function call is finished. Also, the function is likely to be running for several hours (and possibly even weeks!) so the size of the file might be an issue if its constantly being appended too.
Requirements: I need this app to be c++ and to run on both windows and linux (but have no problem with conditional compile statements if need be). I would also like to be able to still see my cout and cerr messages on the console (just not the printf).
My googling has removed my will to live! Can anyone help with a solution via either code example or pointers to places I should be looking for an answer?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以做的是:
读取和写入应该在不同的线程中进行,否则您的程序可能会在管道的一端陷入困境。
以下是如何在 unix 和 UNIX 中进行重定向的示例。 windows:
此代码应该打印
(我在这里使用断言,因为我懒得对此示例进行真正的错误检查)
What you can do is:
Reading and writing should happen in different threads or you risk that your program starves on one end of the pipe.
Here's a sample how to do the redirection in unix & windows:
This code should print
(I'm using assert here, because I am too lazy to do real error checking for this example)
将库封装到应用程序中,并将应用程序的输出通过管道传输到您的应用程序。现在编写一个脚本,这样您就不必每次都使用管道一起运行应用程序。
Encapsulate the lib into an application, and pipe the application's output to your application. Now write a script so that you don't have to run the apps together every time with a pipe.
看一下: http://www.unix.com/programming/ 136225-reading-stdout-pipe.html 看起来很有希望,但我从未尝试过。
Take a look at: http://www.unix.com/programming/136225-reading-stdout-pipe.html it seems promising, but i never tried it.