Two functions to read and write files : ReadFileToMem and WriteFileToDisc
ReadFileToMem :
.386
.model flat,stdcall
option casemap:none
include filefunc.inc
READFILE_MEMINFO STRUCT
hHeap DWORD ?
hMem DWORD ?
FileSize DWORD ?
READFILE_MEMINFO ENDS
PUBLIC ReadFileToMem@8
.code
; ReadFileToMem PROC pFileName:DWORD,pMemInfo:DWORD
; pFileName : pointer to name of the file
; pMemInfo : pointer to structure for allocated memory information
; Return values : if the function succeeds, eax is NULL.
; if the function fails, the return value contains the error code
ReadFileToMem@8:
sub esp,5*4 ; reserve 20 bytes for the local variables
push esi
mov esi,DWORD PTR [esp+32]
invoke GetProcessHeap
test eax,eax
jne @f
mov eax,1
jmp error
@@:
mov DWORD PTR [esp+8],eax ; save the handle of the process heap
mov READFILE_MEMINFO.hHeap[esi],eax
invoke CreateFile,DWORD PTR [esp+52],GENERIC_READ,0,0,\
OPEN_EXISTING,FILE_ATTRIBUTE_ARCHIVE,0
cmp eax,INVALID_HANDLE_VALUE
jne @f
mov eax,2
jmp error
@@:
mov DWORD PTR [esp+20],eax ; save the handle of file
invoke GetFileSize,eax,0
mov DWORD PTR [esp+12],eax ; save the file size
mov READFILE_MEMINFO.FileSize[esi],eax
invoke HeapAlloc,DWORD PTR [esp+16],HEAP_ZERO_MEMORY,eax
mov DWORD PTR [esp+8],eax ; save the address of the allocated memory
mov READFILE_MEMINFO.hMem[esi],eax
lea ecx,DWORD PTR [esp+16] ; get the address of number of bytes read
invoke ReadFile,DWORD PTR [esp+36],eax,DWORD PTR [esp+20],ecx,0
test eax,eax
jnz @f
mov eax,3
jmp error
@@:
invoke CloseHandle,DWORD PTR [esp+20]
xor eax,eax
error:
pop esi
add esp,5*4 ; balance the stack
ret 2*4
; ENDP ReadFileToMem
END
WriteFileToDisc :
.386
.model flat,stdcall
option casemap:none
include filefunc.inc
PUBLIC WriteFileToDisc@12
.code
; WriteFileToDisc PROC pFileName:DWORD,pMemory:DWORD,nSize:DWORD
; pFileName : pointer to name of the file
; pMemory : address of buffer to write file
; nSize : number of bytes to write
; Return values : if the function succeeds, eax is non-NULL
; : if the function fails, the return value is NULL
WriteFileToDisc@12:
sub esp,2*4 ; reserve 8 bytes for the local variables
invoke CreateFile,DWORD PTR [esp+36],GENERIC_WRITE,0,0,\
CREATE_ALWAYS,FILE_ATTRIBUTE_ARCHIVE,0
cmp eax,INVALID_HANDLE_VALUE
jne @f
xor eax,eax
jmp finish
@@:
mov DWORD PTR [esp],eax ; save the handle of file
lea ecx,DWORD PTR [esp+4] ; get the address of number of bytes written
invoke WriteFile,eax,DWORD PTR [esp+28],DWORD PTR [esp+28],ecx,0
test eax,eax
jz finish
invoke CloseHandle,DWORD PTR [esp]
finish:
add esp,2*4 ; balance the stack
ret 3*4
; ENDP WriteFileToDisc
END