三种方法cmd输出重定向(推荐boost.process)

  有些场景需要通过执行cmd命令,并且获取返回的结果。有三种方法:  

  1. boost.process
  2. windows api
  3. _popen

1.boost.process 

#include "boost/process.hpp"
#include "boost/process/windows.hpp"


std::string GetCmdResult(std::string cmd)
{
	namespace bp = boost::process;
	std::string strResult;
	std::error_code ec;
	bp::ipstream is;
	bp::system(cmd, bp::std_out > is, ec,boost::process::windows::create_no_window);
	if (!ec)
	{
		char sz[1024] = { 0 };
		is.read(sz, 1024);
		strResult = sz;
	}
	return strResult;
}

2.windows api 

	std::string GetCmdResult(std::string cmd)
	{
		std::string strResult;
		SECURITY_ATTRIBUTES saPipe;
		saPipe.nLength = sizeof(SECURITY_ATTRIBUTES);
		saPipe.lpSecurityDescriptor = NULL;
		saPipe.bInheritHandle = TRUE;

		HANDLE hReadPipe, hWritePipe;
		BOOL bSuccess = CreatePipe(&hReadPipe,
			&hWritePipe,
			&saPipe,
			0);
		if (!bSuccess)
			return "";

		PROCESS_INFORMATION pi;
		STARTUPINFOA si;
		memset(&si, 0, sizeof(si));
		GetStartupInfoA(&si);
		si.hStdError = hWritePipe;
		si.hStdOutput = hWritePipe;
		si.wShowWindow = SW_HIDE; //隐藏命令行窗口
		si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
		std::vector cmdline(cmd.begin(), cmd.end());
		cmdline.push_back(0);
		if (CreateProcessA(NULL, &cmdline[0], NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
		{
			DWORD dwRet = WaitForSingleObject(pi.hProcess, 3*1000);
			char result[1024] = { 0 };
			DWORD dw;
			ReadFile(hReadPipe, result, 1024, &dw, NULL);
			strResult = result;
			CloseHandle(pi.hThread);
			CloseHandle(pi.hProcess);
		}

		CloseHandle(hReadPipe);
		CloseHandle(hWritePipe);
		return strResult;
	}

 

3. _popen创建一个管道,通过管道读取cmd输出的结果

	std::string GetCmdResult(QString cmd)
	{
		std::string strResult;
		char result[1024] = { 0 };
		auto file = _popen(strResult.c_str(), "r");
		if (nullptr != file)
		{
			while (fgets(result, 1024, file) != nullptr)
			{
				strResult += result;
			}
			_pclose(file);
		}
		return strResult;
	}

这个方法有缺陷,不能等到cmd执行完成后,获取结果,所以有时候获取的数据不完整。

 

 

 

你可能感兴趣的:(Boost,C++)