如何在wchar_t中使用WriteFile()和ReadFile()

问题描述 投票:0回答:1

我使用此代码,该代码使用管道通过应用程序的用户执行命令。使用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;
}

问题是结果为空。

如何修复我的代码?

c++ winapi pipe wchar-t writefile
1个回答
0
投票

一些提示:

  • 添加错误检查以查看ReadFile API调用失败还是dwNumberOfBytesRead)为零。
  • 写宽字符以读取宽字符。例如这样的例子: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;
© www.soinside.com 2019 - 2024. All rights reserved.