SEEK Statement

Syntax

Syntax: SEEK #n, position
Source: pb_cg_emit_seek (pb_codegen.c:6132)

Description

The SEEK statement sets the file pointer for file number #n to the specified 1-based record position. This controls where the next GET or PUT operation will read from or write to. The meaning of position depends on the file mode:

Internally, the 1-based position is converted to a 0-based byte offset and the Win32 SetFilePointer function is called with FILE_BEGIN to reposition the file pointer.

Note: Do not confuse the SEEK statement with the SEEK function. The function form SEEK(#n) returns the current byte position without moving the file pointer. See LOC / SEEK Functions for details.

Parameters

ParameterDescription
nThe integer file number. The file must be open for BINARY or RANDOM access.
positionA numeric expression giving the 1-based record position (RANDOM) or byte position (BINARY). If position is less than 1, it is clamped to 1.

Example

TYPE Record
    id AS LONG
    nam AS STRING * 20
END TYPE

FUNCTION PBMAIN() AS LONG
    LOCAL rec AS Record
    LOCAL i AS LONG

    OPEN "data.dat" FOR RANDOM AS #1 LEN = 24

    ' Read records in reverse order
    FOR i = 10 TO 1 STEP -1
        SEEK #1, i           ' jump to record i
        GET #1, rec           ' read record at that position
        PRINT rec.id, rec.nam
    NEXT i

    CLOSE #1
    FUNCTION = 0
END FUNCTION

Binary Mode Seek

OPEN "data.bin" FOR BINARY AS #2

SEEK #2, 100            ' seek to byte position 100 (offset 99)
GET #2, var             ' read next value at byte 100

SEEK #2, 200            ' seek to byte position 200 (offset 199)
PUT #2, var2            ' write at byte 200

CLOSE #2

Generated Assembly

; Convert 1-based position to 0-based byte offset
; RANDOM mode: offset = (position - 1) * record_length
; BINARY mode: offset = (position - 1) * 1

cmp    rax, 1                           ; check position >= 1
jge    __pb_seek_positive
xor    rax, rax                         ; clamp to 0 if < 1
jmp    __pb_seek_ready
__pb_seek_positive:
sub    rax, 1                           ; 1-based -> 0-based
imul   rax, <multiplier>               ; record_length (RANDOM) or 1 (BINARY)
__pb_seek_ready:
mov    rcx, [rbp - handle_offset]       ; file handle
mov    rdx, rax                         ; lDistanceToMove (low 32 bits)
xor    r8, r8                           ; lpDistanceToMoveHigh = NULL (no 64-bit seek)
xor    r9, r9                           ; dwMoveMethod = FILE_BEGIN (0)
call   [__imp_SetFilePointer]

Seek vs SetFilePointer Parameters

SEEK PositionModeMultiplierSetFilePointer offset
1BINARY10 (beginning of file)
100BINARY199
1RANDOM LEN=40400 (beginning of file)
5RANDOM LEN=4040160
1RANDOM LEN=1281280 (beginning of file)
3RANDOM LEN=128128256

Imported WinAPI Functions

FunctionDLLPurpose
SetFilePointerkernel32.dllMove the file pointer to a specified byte offset from the beginning of the file

Notes