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.
September 15th, 2011 on 12:36
I am going to have to post a link to this blog and its FASM related content; they are always looking for examples the likes of what is easily available here.
As an un-official thanks on their behalf — thank you.
I am sure they will be quite pleased.
September 15th, 2011 on 12:38
FASM Message Board at the official site for FASM as a non-commercial solicitation; everyone that knows about FASM already knows this, but it seemed improper to let it go as understood.
My apologies.
March 16th, 2012 on 18:05
Thanks! 🙂
November 8th, 2013 on 08:49
Thanks a lot from Kazakhstan! That’s really helpfull, since there’s a few of assembly sources at FASM in internet!!!