2014-11-04 43 views
0

我編程在Windows 7中,使用MS Visual C++ 2010寫值,得到運行時檢查錯誤

我使用,我可以訪問的錯誤代碼是這樣的API:

// iResult holds the error codes 
lResult.GetCodeString() 

我需要在文本文件中編寫此代碼。因此,這裏是我是如何進行的:

char buff[10]; 

strcpy (buff, lResult.GetCodeString()); 

pFile_display = fopen ("D:\\ABCD\\myfile_display.txt","a+"); 
fputs("\nthe error vlaue returned is ", pFile_display); 
fwrite (buff, sizeof(char), sizeof(buff), pFile_display); 

是否有這樣做的更好的方式,因爲我正在運行時檢查錯誤,我懷疑我錯在這裏做一些事情。

回答

1

是的,這是一個破碎的做法。

  1. 你不知道錯誤信息有多長,但你只保留10個字符的空間。這並不是很多。
  2. 在將消息寫入文件之前,絕對不需要將消息複製到第二個緩衝區中。
  3. 使用sizeof來計算字符串長度被破壞。
  4. 當您的數據是字符串時,不需要使用旨在寫入二進制數據的低級函數(即fwrite())。

只要做到:

fprintf(pFile_display, "The error is '%s'\n", lResult.GetCodeString()); 

順便說一句,this random Google hit暗示的GetCodeString()返回值也許不是C字符串。你應該這樣做:

fprintf(pFile_display, "The error is '%s'\n", lResult.GetCodeString().GetAscii()); 

得到正確的格式。當然,你應該得到這個編譯器警告。

+0

謝謝。順便說一句,「破」 – user3891236 2014-11-04 12:36:55

+0

@ user3891236我的意思是「不工作」,「不正確」,「無功能」等。通常認爲不起作用的代碼被破壞。 – unwind 2014-11-04 12:49:06

+0

我從你的sprintf得到了這個聲明,錯誤返回的是'°ôZ\\\\\\\\\\\\\\\\\\\\\\'列表太長' 。這裏有什麼不對? – user3891236 2014-11-04 13:27:44