beta.blog

FASM: Get Filesize

by on Dec.08, 2011, under Programming

I recently needed to determine the size of a file in flat assembler. After doing some research I found a useful Windows function called GetFileSizeEx. The disadvantage of this function is that according to MSDN the minimum supported client is Windows XP. Since my application was meant to be for Windows XP or higher I didn’t really bother though.

The sample code below shows how to get the size of a file (description below):

format PE console
entry start

include 'win32a.inc'

;======================================
section '.data' data readable writeable
;======================================

lpString1        db "Filesize: %d",10,0
lpFileName       db "test.txt"
lpFileSize       dd 0

;=======================================
section '.code' code readable executable
;=======================================

start:
        invoke  CreateFile, lpFileName, GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, 0
        cmp     eax, INVALID_HANDLE_VALUE
        jz      .closeHandle
        mov     ebx, eax
        invoke  GetFileSizeEx,ebx,lpFileSize

        ccall   [printf],lpString1,[lpFileSize]
.closeHandle:
        invoke  CloseHandle, ebx


        ccall   [getchar]                   ; I added this line to exit the application AFTER the user pressed any key.
        stdcall [ExitProcess],0             ; Exit the application

;====================================
section '.idata' import data readable
;====================================

library kernel,'kernel32.dll',\
        msvcrt,'msvcrt.dll'

import  kernel,\
        ExitProcess,'ExitProcess',\
        CreateFile,'CreateFileA',\
        GetFileSizeEx,'GetFileSizeEx',\
        CloseHandle,'CloseHandle'

import  msvcrt,\
        printf,'printf',\
        getchar,'_fgetchar'

Short description of the code:
1. Get a file handle of our file “test.txt” (CreateFile)
2. Make sure we got a valid handle (cmp eax,INVALID_HANDLE_VALUE)
3. If we didn’t, jump to close handle
4. Save the handle to EBX (not really necessary for this example but I added it anyways)
5. GetFileSizeEx, use our handle stored at EBX and save the size to lpFileSize
6. Print the size we just determined (printf)
7. Never forget to close the handle


Leave a Reply

*

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!