Page 1 of 1

New to SB and File handling

Posted: Thu Mar 18, 2021 12:30 pm
by David Crosswell
I used to program in Basic on a BBC Micro which died in about 1990. Just started again with SB but I can't get going with Files-writng or retrieving data. Nothing I try seems to work. I am writing something to help me learn French vocabulary and am storing words as DATA.
I just need a few lines of code to store the values of three numeric variables in Files(in the directory I'm running the program from) so I can go back to where I left off when starting the program again.
Any help on this welcome.

Re: New to SB and File handling

Posted: Thu Mar 18, 2021 7:28 pm
by Mr. Kibernetik
David Crosswell wrote:
Thu Mar 18, 2021 12:30 pm
I just need a few lines of code to store the values of three numeric variables in Files(in the directory I'm running the program from)

Code: Select all

a=5
b=20
c=40
file "data.txt" print a;b;c

Re: New to SB and File handling

Posted: Thu Mar 18, 2021 7:42 pm
by matt7
What is the expected range of values for your numeric variables? For example, if they are limited to the range 0-255 then FILE WRITE and FILE READ can be used, which write and read a single byte. But other numeric values will require some additional code to preserve precision.

The below example uses FILE WRITELINE and FILE READLINE with conversions between numeric and string as needed. But note that decimal values or large values may cause them to be written in scientific notation which will make you lose precision. For integers between -999,999 and 999,999 this should work.

Code: Select all

file$ = "storedvars.txt"

var1 = 123
var2 = 456
var3 = 789
STORE_VALUES(file$, var1, var2, var3)

RETRIEVE_VALUES(file$)
var1 = RETRIEVE_VALUES.var1
var2 = RETRIEVE_VALUES.var2
var3 = RETRIEVE_VALUES.var3

'====================================

' Store three numeric values to a file
DEF STORE_VALUES (file$, var1, var2, var3)
  IF FILE_EXISTS(file$) THEN
    ' Erase the file
    FILE file$ SETPOS 0
    FILE file$ TRIM 0
  END IF
  FILE file$ WRITELINE STR$(var1)
  FILE file$ WRITELINE STR$(var2)
  FILE file$ WRITELINE STR$(var3)
END DEF

' Retrieve three numeric values from a file
DEF RETRIEVE_VALUES (file$)
  IF FILE_EXISTS(file$) THEN
    FILE file$ SETPOS 0
    FILE file$ READLINE var$
    var1 = VAL(var$)
    FILE file$ READLINE var$
    var2 = VAL(var$)
    FILE file$ READLINE var$
    var3 = VAL(var$)
  ELSE
    var1 = 0    ' Default values if file$ does not exist
    var2 = 0
    var3 = 0
  END IF
END DEF