by Richard Russell, July 2006
BBC BASIC does not provide any built-in means of writing entire data structures to a file and reading them back again. Ideally it would be nice if one could say “PRINT #file%,struct{}“ and “READ #file%,struct{}“, but unfortunately these statements are not syntactically valid.
However it is quite straightforward to achieve the same effect using calls to API functions. To write an entire structure struct{} to the file opened on channel file% use the following code:
BB4W:
SYS "WriteFile", @hfile%(file%), struct{}, DIM(struct{}), ^temp%, 0
BBCSDL:
SYS "SDL_RWwrite", @hfile%(file%), struct{}, DIM(struct{}), 1
Generic (e.g. BBCTTY):
DEF PROCwritestruct(F%, s{}) LOCAL s$ : PTR(s$)=s{} : !(^s$+4)=DIM(s{}) : BPUT#F%,s$; : !(^s$+4)=0 ENDPROC
Similarly to read an entire structure struct{} from the file opened on channel file% do the following:
BB4W:
SYS "ReadFile", @hfile%(file%), struct{}, DIM(struct{}), ^temp%, 0
BBCSDL:
SYS "SDL_RWread", @hfile%(file%), struct{}, DIM(struct{}), 1
Generic (e.g. BBCTTY):
DEF PROCreadstruct(F%, s{}) LOCAL s$ : PTR(s$)=s{} : !(^s$+4)=DIM(s{}) : s$=GET$#F% BY LENs$ : !(^s$+4)=0 ENDPROC
It is best not to mix these statements with conventional BASIC file reads and writes, but if you do you must flush BASIC's file buffers before each of the API calls, as follows:
PTR#file% = PTR#file% SYS "WriteFile", @hfile%(file%), struct{}, DIM(struct{}), ^temp%, 0 PTR#file% = PTR#file% SYS "ReadFile", @hfile%(file%), struct{}, DIM(struct{}), ^temp%, 0
This technique does not work for structures containing strings or string arrays. In that case it is probably easier simply to write the individual structure members to file one at a time and read them back again. However see the article Storing structures containing strings for details of an alternative method.