Programming
FASM: Read File
by admin on Feb.20, 2011, under Programming
The example code below will open and read a text file. In order to use ReadFile in flat assembler you either have to include ‘WIN32AX.INC’ or handle the imports from kernel32.dll manually. I’ve used the shorter version and included win32ax.in.
After the file has been read, I display the result of ReadFile in a MessageBox. This sample code should work on all operating systems using the Win32 API:
format pe console 4.0 include 'WIN32AX.INC' .data FileTitle db 'file.txt',0 hFile dd ? nSize dd ? lpBytesRead dd ? lpBuffer rb 8192 MessageBoxCaption db 'Output:',0 .code main: invoke CreateFile, FileTitle, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ; Open the file (to get its handle) ; TODO: TestApiError mov [hFile], eax ; Save the file's handle to hFile invoke GetFileSize, [hFile], 0 ; Determine the file size ; TODO: TestApiError mov [nSize], eax ; Save the file size given by EAX invoke ReadFile, [hFile], lpBuffer, [nSize], lpBytesRead, 0 ; Now read the full file ; TODO: TestApiError invoke CloseHandle, [hFile] ; Handle should be closed after the file has been read invoke MessageBox, NULL, addr lpBuffer, addr MessageBoxCaption, MB_OK ; Easy way of outputing the text invoke ExitProcess, 0 .end main
Please make sure the file file.txt exists (in the same directory as your application), else it will crash, as I’ve done no error handling in order to keep the code short.