User Tools

Site Tools


storing_20structures_20in_20files

Storing structures in files

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

Important note:

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.

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
storing_20structures_20in_20files.txt · Last modified: 2024/01/12 22:46 by richardrussell