我使用此代码,该代码使用管道通过应用程序的用户执行命令。使用WriteFile()
和ReadFile()
。
std::string executeCommand(LPCVOID myData, int size, HANDLE hinWrite, HANDLE houtRead)
{
DWORD dw;
char* pbuff = new char[1024 * 128];
WriteFile(hinWrite, myData, size, &dw, NULL);//send command to cmd.exe
Sleep(100);//wait command execute and cmd outputs
ReadFile(houtRead, pbuff, 1024 * 128, &dw, NULL);
pbuff[dw] = 0;
std::string commandResult(pbuff);
delete[] pbuff;
return commandResult;
}
代码运行完美,现在我想用它返回std::wstring
。
我尝试将其转换:
std::wstring executeCommand(LPCVOID myData, int size, HANDLE hinWrite, HANDLE houtRead)
{
DWORD dw;
wchar_t pbuff[1024];
WriteFile(hinWrite, myData, size, &dw, NULL);//send command to cmd.exe
Sleep(100);//wait command execute and cmd outputs
ReadFile(houtRead, pbuff, 1024 * 128, &dw, NULL);
pbuff[dw] = 0;
std::wstring commandResult(pbuff);
std::wcout << L"Result" << commandResult << std::endl;
return commandResult;
}
问题是结果为空。
如何修复我的代码?
一些提示:
ReadFile
API调用失败还是dw
(NumberOfBytesRead
)为零。 wchar_t myData[] = L"hello world";
sizeof
而不是硬编码。您可以参考的工作代码示例:
wchar_t myData[] = L"hello world";
DWORD size = sizeof(myData);
DWORD dw;
wchar_t pbuff[1024];
if (!WriteFile(hinWrite, myData, size, &dw, NULL))//send command to cmd.exe
{
printf("WriteFile fails with error: %d\n", GetLastError());
}
Sleep(100);//wait command execute and cmd outputs
if(!ReadFile(houtRead, pbuff, sizeof(pbuff), &dw, NULL))
{
printf("ReadFile fails with error: %d\n", GetLastError());
}
pbuff[dw] = 0;
std::wstring commandResult(pbuff);
std::wcout << L"Result" << commandResult.c_str() << std::endl;