Blitz3D+ Command Reference

SeekFile ( file_stream,pos )

Parameters

file_stream - file handle returned by ReadFile, WriteFile or OpenFile

pos - new position, in bytes from the start of the file (0 = first byte; must not be negative)

Description

Moves the read/write position within a file.

Returns the new position, or -1 if the seek failed. This is what turns a file from a one-way tape into random-access storage: jump straight to the record you want instead of reading everything before it.

To find an offset, count bytes: an int is 4 bytes, a float 4, a short 2, a byte 1. A file of ints has its 7th value at offset (7-1)*4 = 24. Fixed-size records make this arithmetic trivial; strings do not, because their size depends on their contents - which is why formats you plan to seek around in should stick to fixed-size fields.

Seeking beyond the end of the file is not an error, but there is nothing there: reads return zeros and empty strings. A negative position raises a runtime error.

See also: FilePos, OpenFile, ReadFile, WriteFile.

Example

; SeekFile Example
; ----------------

; Save best scores for levels 1 to 5 (one 4-byte integer each)
file=WriteFile("demo_scores.dat")
For level=1 To 5
    WriteInt file,level*1000
Next
CloseFile file
Print "Saved scores 1000..5000 for levels 1 to 5"

; SeekFile jumps straight to a byte offset in the file.
; The Nth integer sits at offset (N-1)*4, so level 4 is at offset 12
file=ReadFile("demo_scores.dat")
SeekFile file,(4-1)*4
Print "Level 4 score: "+ReadInt(file)

; Seek back to the start and read level 1
SeekFile file,0
Print "Level 1 score: "+ReadInt(file)
CloseFile file

; Clean up the demo file
DeleteFile "demo_scores.dat"
Print "Deleted demo_scores.dat"

Print ""
Print "Press any key to close the example"
WaitKey

End

Index