SEEK statement

Purpose:

SEEK sets the next read or write position in a file.

Syntax:

SEEK hFile AS FILE, Offset AS LONGLONG
 [, Option AS STRING])

Parameters:

  • Data type: FILE
    hFile The handle of file in which read or write position will be set.
  • Data type: LONGLONG
    Offset The read or write position in the file. The initial location of the file pointer is 0.
  • Data type: STRING
    Option One of as a literal argument.
    The default, if Option is not explicitly stated, is SEEK_SET which positions the file pointer at 0.

Example 1:

This example will move the file pointer to byte 8192 in the file.

SEEK FP1, 8192

Example 2:

The example below will move the file pointer to byte 8199 in the file.

SEEK FP1, 8192
SEEK FP1, 7, SEEK_CUR

Example 3:

DIM AS INTEGER EndOfTheLine
DIM AS STRING AddNewLine

OPEN "test.bas" FOR BINARY AS FP1
SEEK FP1, -1, SEEK_END
EndOfTheLine = GETC(FP1)
IF EndOfTheLine <> 10 THEN
  PRINT " No new-line at end of file!"
  INPUT "Do you want to add new-line at end of file ? y/n : ", AddNewLine
  IF INSTR(UCASE$(AddNewLine), "Y") THEN
    SEEK FP1, 0, SEEK_END
    PUTC(FP1, 10)
  END IF
ELSE
  PRINT " New-line at end of file."
END IF
CLOSE FP1

BCX Console Sample Programs using the SEEK statement.

FTELL function

Purpose:

FTELL gets the current position of a file pointer.

Syntax:

FilePtrPosition = FTELL(hFile AS FILE)

Return Value:

  • Data type: LONGLONG
    FilePtrPosition The position of the hFile file pointer.

Parameters:

  • Data type: FILE
    hFile Handle of the file of which the file pointer position is to be retrieved.

Example:

DIM A$ * 666
DIM AS LONGLONG FilePtrPosition

OPEN "DATA.BIN" FOR BINARY NEW AS FilePtr1
A$ = REPEAT$(500, CHR$(RND2(32, 127)))
PUT$  FilePtr1, A$, LEN(A$)
CLOSE FilePtr1

CLS

OPEN "DATA.BIN" FOR BINARY INPUT AS FilePtr1

SEEK   FilePtr1, 123
FilePtrPosition = FTELL(FilePtr1)
PRINT FilePtrPosition

SEEK   FilePtr1, 456
FilePtrPosition = FTELL(FilePtr1)
PRINT FilePtrPosition

CLOSE  FilePtr1

Result:

123
456