读取控制台输出

来源:互联网 发布:董洁的冷清秋知乎 编辑:程序博客网 时间:2024/04/30 12:54


#include <stdio.h>#include <Shlwapi.h>//////////////////////////////////////////////////////////////////////////template <typename CallbackT>BOOL ShellCommand(LPSTR lpszCmdLine, CallbackT funCallback, DWORD dwContext){STARTUPINFOAstartupInfo;PROCESS_INFORMATIONprocessInfo;SECURITY_ATTRIBUTES securityAttributes = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE, };HANDLE hPipeRead= NULL;HANDLE hPipeWrite= NULL;CHAR szBuffer[1024*8] = { 0 };DWORD dwBytesRead= 0;BOOL bFlag = FALSE;//////////////////////////////////////////////////////////////////////////ZeroMemory(&startupInfo, sizeof(startupInfo));ZeroMemory(&processInfo, sizeof(processInfo));if (!::CreatePipe(&hPipeRead, &hPipeWrite, &securityAttributes, 0)) {goto Exit;}startupInfo.cb= sizeof(STARTUPINFO);::GetStartupInfoA(&startupInfo);startupInfo.hStdError= hPipeWrite;startupInfo.hStdOutput= hPipeWrite;startupInfo.wShowWindow= SW_HIDE;startupInfo.dwFlags= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;if (!::CreateProcessA(NULL, lpszCmdLine, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &startupInfo, &processInfo)) {goto Exit;}::CloseHandle(hPipeWrite);hPipeWrite = NULL;do {if (!::ReadFile(hPipeRead, szBuffer, sizeof(szBuffer)-1, &dwBytesRead, NULL)) {break;}funCallback(szBuffer, dwContext);} while (::WaitForSingleObject(processInfo.hProcess, 0) == WAIT_TIMEOUT);bFlag = TRUE;Exit:if (hPipeRead == NULL) {::CloseHandle(hPipeRead);hPipeRead = NULL;}if (hPipeWrite == NULL) {::CloseHandle(hPipeWrite);hPipeWrite = NULL;}return bFlag;}//////////////////////////////////////////////////////////////////////////void Print(LPCSTR lpszText, DWORD dwContext){printf("%s\n", lpszText);}//////////////////////////////////////////////////////////////////////////int main(){ShellCommand("cmd /C dir d:", Print, 0);return 0;}

0 0
原创粉丝点击