2010-12-14 89 views
1

問題WriteFile的字符串字節長度會導致崩潰

我一直在嘗試各種字節計數試圖讓WriteFile工作。問題是它寫入文件後立即崩潰。所有文本都在文件中,但是「程序已經崩潰,發送給微軟?」錯誤對話框彈出。

註釋掉調用WriteFile及其下的所有內容時,程序運行正常,不會崩潰。但是,當我取消註釋WriteFile並將所有代碼保留在下面時,它再次將其註釋掉,從而增加了它的難題。代碼如下,如果有人可以看到我錯過的東西,非常感謝:-)

字節長度我試過了。

我曾嘗試23,24(字符串長度+空),25(也許我忘了字節)的字節長度,也只是用SIZEOF WRITETEXT和他們都:-(失敗。

代碼

.386 
.model flat,stdcall 
option casemap:none ; Case Sensitive 

; Windows 
include \masm32\include\windows.inc 

; Kernel32 
include \masm32\include\kernel32.inc 
includelib \masm32\lib\kernel32.lib 

.data 
FilePath   db "C:\test.txt",0 
WriteText  db "This is some test text." 

.code 
start: 

; Edit a file 

invoke CreateFile, addr FilePath, GENERIC_WRITE, FILE_SHARE_WRITE or FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL 
push eax ; save the file handle 

; This works other than the crashing, any number less then 23 
; and the file has some of the text clipped 
; any larger and NUL is appended until the byte count is matched. 
invoke WriteFile, eax, addr WriteText, 23, NULL, NULL 

pop eax 
push eax 

invoke CloseHandle, eax 

invoke ExitProcess, 0 
end start 

回答

4

根據the documentation for the WriteFile function

lpNumberOfBytesWritten [出,可選]
[...]
只有當lpOverlapped參數不爲NULL時,此參數纔可以爲NULL。

您將lpNumberOfBytesWritten和lpOverlapped都設置爲NULL。通過addr some_writable_variable作爲lpNumberOfBytesWritten,它應該工作。

+0

Doh!我將其讀爲「lpNumberOfBytesWritten [out,optional] [...]只有當lpOverlapped參數爲NULL時,此參數纔可以爲NULL。」 (因爲在兩個都必須爲空謝謝。 – Zimm3r 2010-12-14 01:31:20