Syntax:result = LOF(#n) Source: PowerBASIC built-in function, implemented via GetFileSize
Description
Returns the total length of the file associated with file number #n, in bytes. LOF (Length Of File) is a standard PowerBASIC function commonly used to determine file size before allocating buffers, to validate that a file is not empty, or to monitor file growth during logging.
Internally, LOF calls the Win32 GetFileSize function on the stored file handle. The returned value is the total number of bytes in the file, regardless of the current file pointer position.
Parameters
Parameter
Description
n
The integer file number (1 to 255). The file must be open.
Return Value
Value
Meaning
0
File is empty (0 bytes).
> 0
File size in bytes. For example, LOF(1) returns 1024 for a 1 KB file.
0 (error)
If the file number is not open, the result is undefined (may return 0).
Example
FUNCTION PBMAIN() AS LONG
LOCAL data AS STRING
LOCAL size AS LONG
OPEN "input.txt" FOR INPUT AS #1
' Get file size
size = LOF(1)
PRINT "File size: "; size; " bytes"
IF size = 0 THEN
PRINT "File is empty!"
ELSE
' Allocate a string buffer large enough for the entire file
data = SPACE$(size)
' ... read data ...
END IF
CLOSE #1
FUNCTION = 0
END FUNCTION
Checking File Size in Binary Mode
OPEN "data.bin" FOR BINARY AS #2
IF LOF(2) = 0 THEN
PRINT "No records in file"
CLOSE #2
EXIT FUNCTION
END IF
' Calculate number of records (each 8 bytes)
PRINT "Number of records: "; LOF(2) \ 8
CLOSE #2
Generated Assembly
GetFileSize Call
; LOF(#n) implementation via GetFileSize
mov rcx, [rbp - handle_offset] ; hFile = stored file handle
xor rdx, rdx ; lpFileSizeHigh = NULL
; (only 32-bit size supported)
call [__imp_GetFileSize] ; returns file size in EAX
; returns 0xFFFFFFFF on error
; Check for error
cmp rax, -1 ; INVALID_FILE_SIZE == 0xFFFFFFFF
jne __pb_lof_ok
xor rax, rax ; on error, return 0
__pb_lof_ok:
mov [rbp - result_offset], rax ; store result (file size in bytes)