Stage 109: File handling

Follow the development of the SharpBASIC compiler and share your thoughts and ideas.
Locked
User avatar
frank
Site Admin
Posts: 40
Joined: Sun Nov 21, 2021 12:04 pm
Location: Netherlands
Contact:

Stage 109: File handling

Post 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.
Last edited by frank on Sat Jun 24, 2023 12:48 pm, edited 4 times in total.
Keep it simple!
Locked