重定向标准输出错误输出到编辑控件中!

有时候我们需要重定向标准输出(stdout)错误输出(stderr)到编辑控件中:

比如我们作了一个前端编译器,编译的功能由mingw gcc来完成,这时我们要捕获它的编译消息到我们的输出窗口,这时怎么办呢!

很简单,我们需要用匿名管道来实现,参见如下代码:

SECURITY_ATTRIBUTES g_sa = {sizeof(SECURITY_ATTRIBUTES),NULL,TRUE};
void CGccDbgView::OnCompiler() 
{
	// TODO: Add your control notification handler code here

	HANDLE hWritePipe, hReadPipe;
	if ( !CreatePipe( &hReadPipe, &hWritePipe, &g_sa, 0 ) )
	{
		return;
	}


	CString strCmdLine="c:\\gcc.exe test.c";
	// create an environment for the CGI process....
	DWORD dwCreateFlags = 0;

	PROCESS_INFORMATION pi;
	STARTUPINFO si = {0};
	si.cb = sizeof(si);
	si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
	si.wShowWindow = SW_HIDE;
	si.hStdInput = hReadPipe;
	si.hStdOutput = hWritePipe;
	si.hStdError = hWritePipe;
	BOOL bOk = CreateProcess( NULL, strCmdLine.GetBuffer(1),
		NULL, NULL, TRUE,
		dwCreateFlags, NULL,
		"c:\\", &si, &pi );
	strCmdLine.ReleaseBuffer();
	// if created....
	if ( bOk )
	{
	
		char buffer[1024]={0};

		// wait for either cancel or process done....
		WaitForSingleObject(pi.hProcess,INFINITE);
		// release our hold on the thread....
		CloseHandle( pi.hThread );
		// send the body of the post to the stdin....
		DWORD dwWritten = 0;
		ReadFile( hReadPipe, buffer,1024,&dwWritten, NULL );
		m_msg = buffer;
	//	AfxMessageBox(m_msg);
		UpdateData(FALSE);
		// close our hold on it....
		CloseHandle( pi.hProcess );
	}


}

这里m_msg属于编辑器控件变量。这样我们就能在编辑控件中看到结果了。如图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值