Author Topic: confused about the WriteFile function  (Read 42 times)

gelatine1

  • Member
  • **
  • Posts: 106
confused about the WriteFile function
« on: November 24, 2014, 05:56:13 AM »
I wrote some code which was supposed to write some number to a file

Code: [Select]
invoke CreateFile,addr file,GENERIC_WRITE,0,0,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,0
mov hfile,eax
invoke SetFilePointer,hfile,0,0,FILE_END

mov eax,age
mov edi,[pmem]
mov [edi],eax

invoke WriteFile,hfile,edi,1,0,0

invoke CloseHandle,hfile

It crashed. I tried to debug it and i couldn't find anything that made it crash. I remember I had done this before though so I digged into my older projects and I found out that it should've been done like this:

Code: [Select]
invoke CreateFile,addr file,GENERIC_WRITE,0,0,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,0
mov hfile,eax
invoke SetFilePointer,hfile,0,0,FILE_END

mov eax,age
mov edi,[pmem]
mov [edi],eax

xor     ecx,ecx
push    ecx
mov     edx,esp

invoke WriteFile,hfile,edi,1,edx,ecx

pop ecx

invoke CloseHandle,hfile

This code did work, but now I am just very confused about what is happening in this last code with esp and ecx and stuff and I still don't understand why my initial code did not work.
I am confused too about the meaning of the last 2 parameters of the WriteFile function.
Could anyone make this clear to me ?

Thanks in advance
Jannes

jj2007

  • Member
  • *****
  • Posts: 3526
    • MasmBasic
Re: confused about the WriteFile function
« Reply #1 on: November 24, 2014, 08:04:24 AM »
Comments are a fantastic invention, Jannes, they help you to understand your own code ;-)

   push    ecx   ; create a dword on the stack
   mov     edx,esp  ; get its address
   invoke WriteFile,hfile,edi,1,edx,ecx
   pop ecx  ; NumberOfBytesWritten
   invoke CloseHandle,hfile

WriteFile(
    HANDLE hFile,   // handle to file to write to
    LPCVOID lpBuffer,   // pointer to data to write to file
    DWORD nNumberOfBytesToWrite,   // number of bytes to write
    LPDWORD lpNumberOfBytesWritten,   // pointer to number of bytes written
    LPOVERLAPPED lpOverlapped    // pointer to structure needed for overlapped I/O

gelatine1

  • Member
  • **
  • Posts: 106
Re: confused about the WriteFile function
« Reply #2 on: November 24, 2014, 08:15:43 AM »
Alright thank you :) I get it now. Just one more question, What's the point of the lpNumberOfBytesWritten that gets returned ? won't it be the same as nNumberOfBytesToWrite? Or is it possible it get's interrupted or anything similar ?