标准输出(stdout)重定向
2008-11-19 18:34:40
http://blog.chinaunix.net/uid-20786051-id-490729.html
公司有个同事用了一个很老的DLL,其信息都是输出到控制台窗口(console),问能不能将其输出到MFC的view中?
我们知道,标准输出默认情况下是输出到console中。
要将stdout重定向到文件, 比较简单,code如下(MSDN中源码):
//将stdout重定向到文件中
FILE *stream ;
if((stream = freopen("file.txt", "w", stdout)) == NULL)
exit(-1);
printf("this is stdout output ");
//重新将stdout重定向到console
stream = freopen("CON", "w", stdout);
printf("And now back to the console once again ");
但是将stdout重定向某个MFC程序View中显示出来,实现稍有点复杂。总体思路是
1)创建一个匿名管道(pipe)
2)将stdout重定向到这个pipe上
3)创建一个线程,读取pipe中的内容,然后将这些内容输出到你希望输出的地方,譬如一个view里。
启动进程时,先调用StdoutRedirect(),那么这个进程中所有的printf都可以输出到View里。
code如下:
HANDLE hOutputReadTmp = 0;
HANDLE hOutputWrite = 0;
void DisplayError(char* szMsg)
{
TRACE(szMsg);
TRACE(" ");
}
DWORD WINAPI ReadStdout(LPVOID lpvThreadParam)
{
CHAR lpBuffer[256];
DWORD nBytesRead;
while(TRUE)
{
if (!ReadFile(hOutputReadTmp, lpBuffer,sizeof(lpBuffer),
&nBytesRead,NULL) || !nBytesRead)
{
if (GetLastError() == ERROR_BROKEN_PIPE)
break; // pipe done - normal exit path.
else
DisplayError("ReadFile"); // Something bad happened.
}
if (nBytesRead >0 )
{
//获取到printf的输出
lpBuffer[nBytesRead] = 0;
//replace your code here. Do it yourself.
DisplayInView(lpBuffer);
}
}
return 0;
}
void StdoutRedirect()
{
if (!CreatePipe(&hOutputReadTmp,&hOutputWrite,0,0))
DisplayError("CreatePipe");
int hCrt;
FILE *hf;
//AllocConsole();
hCrt = _open_osfhandle(
(long)hOutputWrite,
_O_TEXT
);
hf = _fdopen( hCrt, "w" );
*stdout = *hf;
int i = setvbuf( stdout, NULL, _IONBF, 0 );
// Launch the thread that gets the input and sends it to the child.
DWORD ThreadID;
HANDLE hThread = ::CreateThread(NULL,0,ReadStdout,
0,0,&ThreadID);
}
最后,顺便提一下,如果要redirect某个console进程的stdout,也是类似。MSDN有详细例子。搜索“stdout redirect”即可。
posted on 2005-06-06 18:28 Michael 阅读(3965)
--------------------next---------------------
linux牛牛网
Win32标准输出重定向VS2015通用实现
需积分: 48 37 浏览量
2018-09-28
16:54:38
上传
评论
收藏 6KB ZIP 举报
dj0379
- 粉丝: 1775
- 资源: 90
最新资源
- 批量将py编译为pyd文件.atbx
- Python项目-学生管理系统
- verilog HDL硬件语法设计包括算术运算三人表决器Verilog的阻塞和非阻塞赋值源码例程quartus13.1工程合集
- 【文章话题分类论文】OpenAlex Topic Classification Whitepaper
- linux学习常用命令
- 功率拓扑快速参考指南-ti,TI官方出品
- 开关电源拓朴图表,各种电路拓扑表格
- 登录和注册 前端:vue3+iview plus +axios 后台:spring boot +mybatis
- 软件测试入门简介:从基础到实践的全面介绍
- 2024CDA Level Ⅰ 认证考试大纲
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈