Author Topic: LookAhead function  (Read 241 times)

MrBcx

  • Administrator
  • Hero Member
  • *****
  • Posts: 1850
    • View Profile
LookAhead function
« on: October 17, 2023, 09:49:57 AM »
The FTELL function was recently added to the BCX.  Besides the example in the BCX Help file,
the following might sometimes be useful when reading lines of text from sequential files.  It allows
us to selectively grab the next line of text without changing the current line pointer.  In other words,
in a loop like this, we get a peek at the next line.

WHILE NOT EOF(FP1)
    LINE INPUT FP1, Txt$
    IF LookAhead$(FP1) = Txt$ THEN PRINT "The Next Line is the same as Txt$"
WEND

LookAhead$() gets its super-power from the FTELL and SEEK commands.

Code: [Select]
FUNCTION LookAhead$(FilePointer AS FILE) AS STRING
    LOCAL CurrentPosition AS INTEGER
    LOCAL LINE AS STRING

    ' Get the current file position
    CurrentPosition = FTELL(FilePointer)

    ' Read the next line of text input
    LINE INPUT #FilePointer, LINE

    ' Check if we've reached EOF
    IF EOF(FilePointer) THEN
        ' Restore the file position to the original position
        SEEK FilePointer, CurrentPosition
        ' Return an empty string to indicate EOF
        FUNCTION = ""
    ELSE
        ' Restore the previously saved file position
        SEEK FilePointer, CurrentPosition
        ' Return the text that was retrieved
        FUNCTION = LINE
    END IF
END FUNCTION