2016-01-03 34 views
-1
std::cout << buffer << std::endl; 


if (lastTitle != buffer) { 
    //write new title; 
    WriteFile(file, "\n\nWindow: ", sizeof("\n\nWindow: "), NULL, NULL); 
    WriteFile(file, buffer.c_str(), sizeof(buffer), NULL, NULL); 
    WriteFile(file, "\n", sizeof("\n"), NULL, NULL); 
    std::cout << GetLastError(); //this is showing 0, which means no error 

Cout的輸出:的WriteFile()截斷字符串

C:\用戶\ riseo \桌面\ C++ \ my_proj \調試\ my_proj.exe

正在被寫入到是表示文件:

窗口:C:\用戶\ riseo \桌面\ C++ \米

我不太清楚這是爲什麼被截斷,它應該是一樣什麼COUT正在打印。對不起,這篇文章並沒有顯示出太多的研究,但我一整天都被各種字符串格式相關陷阱燒燬,我不知道這裏發生了什麼。我能想到的只有c_str()會出錯。

+2

「*我已經一整天都被各種各樣的字符串格式相關陷阱燒燬,我不知道這裏發生了什麼*「 - 那麼你顯然不會了解字符串在內存中的表示方式,以及格式化函數/操作符的工作方式。你需要刷新你的C/C++基礎知識。 –

回答

4

您嚴重誤用sizeof()WriteFile()對字節進行操作,但是您傳遞的是字符數據。字符串文字包含一個sizeof()將包含的空終止符,在這種情況下您不需要該終止符。並且std::string()包含一個指向字符數據的指針,所以sizeof(std::string)不包含真正的字符長度。

你需要做這個:

//write new title; 
WriteFile(file, "\n\nWindow: ", strlen("\n\nWindow: "), NULL, NULL); 
WriteFile(file, buffer.c_str(), buffer.length(), NULL, NULL); 
WriteFile(file, "\n", strlen("\n"), NULL, NULL); 

包裝函數會更好:

bool WriteStringToFile(HANDLE hFile, const std::string &str) 
{ 
    return WriteFile(hFile, str.c_str(), str.length(), NULL, NULL); 
} 

... 

//write new title; 
WriteStringToFile(file, "\n\nWindow: "); 
WriteStringToFile(file, buffer); 
WriteStringToFile(file, "\n"); 

一個std::ofstream甚至會更好:

std::ofstream ofs("myfile.txt", std::ios_base::binary); 
... 
ofs << "\n\nWindow: " << buffer << "\n"; 
+0

感謝您指出我的問題並提供這樣優雅的解決方案。 +1 – hydrozoah

+0

第二個調用可以沒有.c_str(),即'WriteStringToFile(file,buffer);',目前你做了一個不必要的轉換std :: string - > const char * - > std :: string。 –