C++取得コンソール出力


</pre><pre name="code" class="cpp">// Test.cpp : Defines the entry point for the console application.
//


//#include "stdafx.h"
#include <conio.h>
#include <stdio.h>
#include <windows.h>
#include <fstream>


using namespace std;


#define   EXECDOSCMD   "ping   www.baidu.com "   //         
std::string ExecDosCmd() 
{ 
SECURITY_ATTRIBUTES   sa; 
HANDLE   hRead,hWrite; 


sa.nLength   =   sizeof(SECURITY_ATTRIBUTES); 
sa.lpSecurityDescriptor   =   NULL; 
sa.bInheritHandle   =   TRUE; 
if   (!CreatePipe(&hRead,&hWrite,&sa,0))   
{ 
return   FALSE; 
}   


STARTUPINFO   si; 
PROCESS_INFORMATION   pi;   
si.cb   =   sizeof(STARTUPINFO); 
GetStartupInfo(&si);   
si.hStdError   =   hWrite; 
si.hStdOutput   =   hWrite; 
si.wShowWindow   =   SW_HIDE; 
si.dwFlags   =   STARTF_USESHOWWINDOW   |   STARTF_USESTDHANDLES; 
//    ,CreateProcess         MSDN 
if   (!CreateProcess(NULL,   EXECDOSCMD 
,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))   
{ 
return   FALSE; 
} 
CloseHandle(hWrite); 


char   buffer[4096]   =   {0}; 
DWORD   bytesRead;   
std::string strOutPut = "";


while   (true)   
{ 
if   (ReadFile(hRead,buffer,4095,&bytesRead,NULL)   ==   NULL) 
break; 
//buffer        ,       ,        
//printf(buffer); 
strOutPut += buffer;
Sleep(200);   
}




return   strOutPut;
}


int main()
{
std::string strOut = ExecDosCmd();


return 0;
}