当前位置:   article > 正文

C++获取控制台输出

c++获取控制台输出
  1. </pre><pre name="code" class="cpp">// Test.cpp : Defines the entry point for the console application.
  2. //
  3. //#include "stdafx.h"
  4. #include <conio.h>
  5. #include <stdio.h>
  6. #include <windows.h>
  7. #include <fstream>
  8. using namespace std;
  9. #define EXECDOSCMD "ping www.baidu.com " //可以换成你的命令
  10. std::string ExecDosCmd()
  11. {
  12. SECURITY_ATTRIBUTES sa;
  13. HANDLE hRead,hWrite;
  14. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  15. sa.lpSecurityDescriptor = NULL;
  16. sa.bInheritHandle = TRUE;
  17. if (!CreatePipe(&hRead,&hWrite,&sa,0))
  18. {
  19. return FALSE;
  20. }
  21. STARTUPINFO si;
  22. PROCESS_INFORMATION pi;
  23. si.cb = sizeof(STARTUPINFO);
  24. GetStartupInfo(&si);
  25. si.hStdError = hWrite;
  26. si.hStdOutput = hWrite;
  27. si.wShowWindow = SW_HIDE;
  28. si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
  29. //关键步骤,CreateProcess函数参数意义请查阅MSDN
  30. if (!CreateProcess(NULL, EXECDOSCMD
  31. ,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
  32. {
  33. return FALSE;
  34. }
  35. CloseHandle(hWrite);
  36. char buffer[4096] = {0};
  37. DWORD bytesRead;
  38. std::string strOutPut = "";
  39. while (true)
  40. {
  41. if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
  42. break;
  43. //buffer中就是执行的结果,可以保存到文本,也可以直接输出
  44. //printf(buffer);
  45. strOutPut += buffer;
  46. Sleep(200);
  47. }
  48. return strOutPut;
  49. }
  50. int main()
  51. {
  52. std::string strOut = ExecDosCmd();
  53. return 0;
  54. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/798274
推荐阅读
相关标签
  

闽ICP备14008679号