With SharpBASIC data can be read from and written to files on disk. SharpBASIC supports three different file types: text files, binary files and random access files. There are several functions and statements to handle files.
The open function is used to open a file:
handle = open(inp "myfile.txt");
The function accepts a filename preceded by a mode clause. In the example, a file is opened for input (inp), which is the mode to read text files. There are five different mode types:
The open function returns a file handle of type hnd, which is a non-negative integer number if the file was opened successfully.
The close statement is used to close a file that was previously opened with the open function.
close(handle);
The close statement accepts a valid file handle of type hnd as parameter.
The read function is used to read text from a text file.
flag = read(handle, text);
The read function accepts two parameters: a valid handle of a text file that was opened for input and a variable or fixed-length string where the text will be stored. The function returns a flag of type integer that is 0 (null) if the read operation was successful:
flag = read(handle, text);
if flag == 0 do
print(text);
end
If the string is a variable (null-terminated) length-string then the read function will try to read the next line in the file. If the string is a fixed-length string then the read function will read the next block of text the size of the string. This means that if a fixed-length string is long enough, a text-file can be read at once.
The write function is used to write text to a text file.
flag = write(handle, text);
The function accepts two parameters: a valid handle of a text file that was opened for output (out) or append(add) and a string expression. The function returns a flag of type integer that is 0 (null) if the write operation was successful:
flag = write(handle, text);
if flag <> 0 do
print("Error writing to file.");
end