Page 1 of 1

Stage 109: File handling

Posted: Tue Jun 20, 2023 6:47 am
by frank
Support for file handling is being added to the SharpBASIC language. The first step is support for text files. In addition, support will be added for binary files and the good old random access file.

With the introduction of file handling, a new datatype is added: the handle type hnd, which is used for files and devices.

Opening and reading a text file looks like this (working example):

Code: Select all

' SharpBASIC read text file
' -------------------------
option strict;

incl "lib/sys.sbi";
incl "lib/io.sbi";

decl sub readFile(const fileName: str);

main do
  readFile("myfile.txt");
end

sub readFile(const fileName: str)
  dim is
    tf: hnd;    ' file handle
    fl: int;    ' flag
    tb: str;    ' text buffer
  end
do
  ' open file for input (read from text file)
  tf = open(inp fileName);
  ' handle < 0 means error
  if tf >= 0 do
    loop do
      while not eof(tf);
      ' read line
      fl = read(tf, tb);
      if fl == 0 do
        print(tb);
      else do
        print("Error reading file " + fileName);
        break;
      end
    end
    close(tf);
  else do
    print("Error opening file " + fileName);
  end
end
With text files, the fixed length string will play a special role, because when passing a fixed length string to the read function, it will override its default buffer size with the size of the string. This way, if the fixed length string is large enough, an entire text file can be loaded at once.