Binary Files

To access a file in binary mode, it must be opened with the OPEN statement. When it is no longer needed, and before the program ends, it must be closed with the CLOSE statement. See also: Filedialog, File Operations, Path and Filename.

In binary access mode, bytes are written to the file or read from the file as characters. See Chr$( n ). Use the SEEK command to seek to the desired point in the file for reading or writing. This sets the file pointer to the location specified. Use the LOC(#handle) function to retrieve the current position of the file pointer. The current position of the file pointer is used when reading or writing data to a binary file.

Data is read from the file with the INPUT statement.

Data is written to the file with the PRINT statement. Binary mode never writes line delimiters when printing to the file. Line delimiters include carriage returns, which are chr$(13) and line feeds, which are chr$(10).

Usage:

  'binary file access
  open "myfile.ext" for binary as #handle

  'seek to file position
  seek #handle, fpos

  'get the current file position
  fpos = loc(#handle)

  'write a byte to the file
  print #handle, chr$(143)

  'read the data at the current location
  input #myfile, txt$

Example Program:

  'binary file example
  open "myfile.bin" for binary as #myfile
  txt$ = "I like programming with Liberty BASIC."
  print "Original data in file is: ";txt$

  'write some data to the file
  print #myfile, txt$

  'retrieve the position of the file pointer
  nowPos = LOC(#myfile)

  'move the filepointer
  nowPos = nowPos - 14
  seek #myfile, nowPos

  'read the data at the current location
  input #myfile, txt$

  'print txt$ in mainwin
  print "Data at ";nowPos;" is: ";txt$

  'move the filepointer
  seek #myfile, 2

  'write some data to the middle of the file
  print #myfile, "love"
  print str$(loc(#myfile) - 2); " bytes written"

  'move the file pointer to the beginning
  seek #myfile, 0

  'read the data
  input #myfile, txt$

  'print data in mainwin
  print "New Data is: ";txt$

  'close the file
  close #myfile
  end