ZetCode

FreeBasic Seek Keyword

Last modified April 22, 2026

The FreeBasic Seek keyword is used to move the file position pointer within an open file. It allows random access to file contents by positioning the pointer at a specific byte location.

Important: File positions in FreeBASIC are 1-based (the first byte is position 1, not 0). The Seek statement and function work with both text and binary files, but binary mode provides more predictable positioning for random access.

Basic Definition

In FreeBASIC, Seek is a statement that changes the current position in a file. It works with both binary and text files opened for random access.

The Seek function returns the current position of the file pointer. Together, these allow precise navigation through file contents. File positions are 1-based in FreeBASIC (first byte is position 1).

Seek Statement Syntax

The Seek statement has this syntax:

Seek #fileNumber, position

fileNumber is the number used when opening the file. position is the new position (1-based) for the file pointer.

Seek Function Syntax

The Seek function has this syntax:

currentPosition = Seek(fileNumber)

It returns the current position of the file pointer for the specified file. This is useful for tracking your location in a file.

Basic Seek Example

This example demonstrates basic file positioning with Seek.

seek_basic.bas
' Create a test file
Dim f As Integer = FreeFile
Open "test.txt" For Output As #f
Print #f, "Hello World"
Close #f

' Read from specific position
Open "test.txt" For Binary As #f  ' Use Binary mode for precise positioning
Seek #f, 7  ' Position 7 is 'W' in "Hello World" + CRLF
Dim buffer As String * 5  ' Fixed-length string for exact byte reading
Get #f, , buffer
Close #f

Print "Read from position 7: "; buffer

We first create a file with some text. Then we reopen it in Binary mode and use Seek to position at byte 7 before reading. Using Get with a fixed-length string reads exactly 5 bytes ("World"). Binary mode provides predictable positioning; text mode may have platform-specific line ending behavior.

Seek with Binary Files

Seek is particularly useful when working with binary files.

seek_binary.bas
Dim f As Integer = FreeFile
Open "data.bin" For Binary As #f

' Write three integers at specific positions
' Each Integer is 2 bytes in FreeBASIC
Seek #f, 1
Put #f, , CShort(100)  ' Use CShort for explicit 2-byte integer
Seek #f, 3  ' 1 + 2 bytes
Put #f, , CShort(200)
Seek #f, 5  ' 3 + 2 bytes
Put #f, , CShort(300)

' Read the second integer
Seek #f, 3
Dim value As Short
Get #f, , value
Close #f

Print "Value at position 3: "; value

This creates a binary file and writes integers at specific positions. We then seek to position 3 and read the value stored there. Each Short (16-bit integer) occupies 2 bytes in FreeBASIC, so we space them accordingly. Using explicit type casts like CShort ensures consistent behavior across platforms.

Using Seek Function

This example shows how to use the Seek function to track file position.

seek_function.bas
Dim f As Integer = FreeFile
Open "positions.txt" For Binary As #f  ' Binary for accurate Seek() values

Print #f, "First line"
Print "Position after first line: "; Seek(f)
Print #f, "Second line"
Print "Position after second line: "; Seek(f)
Print #f, "Third line"
Print "Position after third line: "; Seek(f)

Close #f

As we write lines to the file, we use the Seek function to monitor the current position. Using Binary mode ensures Seek() returns accurate byte positions. In Output mode, line ending conversions may affect the reported position on different platforms.

Random Access with Seek

Seek enables true random access to file contents.

seek_random.bas
' Create file with fixed-length records
Dim f As Integer = FreeFile
Open "random.dat" For Binary As #f

' Write 10 fixed-length records (10 bytes each)
For i As Integer = 1 To 10
    Dim record As String * 10
    record = "Record " + Right(" " + Str(i), 2)
    Put #f, , record
Next
Close #f

' Read records in reverse order using Seek
Open "random.dat" For Binary As #f
For i As Integer = 10 To 1 Step -1
    Seek #f, (i - 1) * 10 + 1  ' Calculate position directly
    Dim s As String * 10
    Get #f, , s
    Print Trim(s)
Next
Close #f

We first create a file with 10 fixed-length records (10 bytes each). Then we reopen it and read the records in reverse order by calculating their positions. Using fixed-length records is essential for reliable random access; variable-length text records cannot be reliably positioned with simple arithmetic.

Seek with Large Files

Seek can handle large files by using Long positions.

seek_large.bas
Dim f As Integer = FreeFile
Open "large.bin" For Binary As #f

' Write data at large positions using Long integers
Seek #f, 1000000
Dim val1 As Long = 12345
Put #f, , val1

Seek #f, 2000000
Dim val2 As Long = 67890
Put #f, , val2

' Read back
Seek #f, 1000000
Dim read1 As Long
Get #f, , read1

Seek #f, 2000000
Dim read2 As Long
Get #f, , read2

Close #f

Print "Values: "; read1; " and "; read2

This demonstrates Seek working with large file positions (millions of bytes). FreeBASIC handles these positions correctly with Long (32-bit) integers. Note that Seek accepts positions up to 231-1 in 32-bit builds; use Integer64 for larger files.

Seek and File Size

Seek can be used with Lof to navigate relative to file size.

seek_filesize.bas
Dim f As Integer = FreeFile
Open "example.bin" For Binary As #f

' Write 100 bytes
For i As Integer = 1 To 100
    Dim b As Byte = CByte(i)
    Put #f, , b
Next

' Read last 10 bytes using Lof (Length Of File)
Dim fileSize As Long = Lof(f)
Seek #f, fileSize - 9  ' Position at 10th byte from end (1-based)

Dim lastBytes(1 To 10) As Byte
For i As Integer = 1 To 10
    Get #f, , lastBytes(i)
Next

Close #f

Print "Last 10 bytes:"
For i As Integer = 1 To 10
    Print lastBytes(i); " ";
Next
Print

We create a binary file with 100 bytes, then use Seek with Lof (length of file) to position near the end. Note: since positions are 1-based, to read the last 10 bytes we seek to Lof(f) - 9, not Lof(f) - 10. This pattern is useful for reading file footers or trailers.

Error Handling with Seek

Proper error handling prevents crashes when seeking to invalid positions.

seek_errors.bas
' Modern error handling for Seek (-lang fb compatible)
Sub TestSeek()
    Dim f As Integer = FreeFile
    Open "test.bin" For Binary As #f
    
    ' Write a small file (10 bytes)
    For i As Integer = 1 To 10
        Put #f, , CByte(i)
    Next
    
    ' Get file size for validation
    Dim fileSize As Long = Lof(f)
    Dim targetPosition As Long = 100000  ' Intentionally invalid
    
    ' Pre-check position before seeking
    If targetPosition >= 1 And targetPosition <= fileSize Then
        Seek #f, targetPosition
        Print "Seek successful"
    Else
        Print "Error: Position "; targetPosition; " is out of range (1-"; fileSize; ")"
        ' Fallback: seek to end of file
        Seek #f, fileSize
    End If
    
    Close #f
End Sub

TestSeek()

This modern approach validates the target position against the file size before attempting to seek. If the position is invalid, we handle it gracefully instead of crashing. This pattern is preferred in new FreeBASIC code over legacy On Error Goto statements.

Best Practices

This tutorial covered the FreeBasic Seek keyword with practical examples showing file positioning in different scenarios.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all FreeBasic Tutorials.