我正在使用CreateProcess通過Cygwin的bash.exe運行bash腳本並重定向輸出(因爲這就是客戶需要的)。要解決的唯一問題是,如果ReadFile沒有填滿lpBuffer,我最終會在它的末尾添加一些垃圾字符,我想過濾掉它們。通常情況下,這是一樣的東西:如何用regex_replace終止一個字符串?
"ÌÌÌÌ...ÌÌÌÌÌuÆì¨õD"
針對下面的代碼給我:
"uÆì¨õD"
所以,我至少部分成功= d
不過,我」 d真的很喜歡在第一個垃圾字符上終止字符串,最好是換行符,但我似乎無法找到fmt的變體。
void ReadAndHandleOutput(HANDLE hPipeRead) {
char lpBuffer[256];
DWORD nBytesRead;
wstringstream wss;
while(TRUE)
{
if(!ReadFile(hPipeRead, lpBuffer, sizeof(lpBuffer), &nBytesRead, NULL) || !nBytesRead)
{
break;
}
// Filter out the weird non-ascii characters.
std::string buffer(lpBuffer);
std::regex rx("[^[:alnum:][:punct:][:space:]]+");
std::string fmt("\n\0");
std::regex_constants::match_flag_type fonly = std::regex_constants::format_first_only;
std::string result = std::regex_replace(buffer, rx, fmt, fonly);
wss << result.c_str();
}
SetWindowText(GetDlgItem(HwndMain, IDC_OUTPUT), LPCWSTR(wss.str().c_str())); }
不應該在函數返回的字節數讀?您可以清空緩衝區的其餘部分。 – nhahtdh 2013-02-27 05:18:28
它的確如此,並且確實證明這是正確的解決方案,只需進行一次修改:我的緩衝區需要比傳遞給ReadFile的最大大小值大一個元素,以便我可以確保它始終爲空。 – phoff 2013-02-28 21:16:50