This is an old revision of the document!
Storing structures in files
by Richard Russell, July 2006
BBC BASIC for Windows 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 the Windows API. To write an entire structure struct{} to the file opened on channel file% use the following code:
SYS "WriteFile", @hfile%(file%), struct{}, DIM(struct{}), ^temp%, 0
Similarly to read an entire structure struct{} from the file opened on channel file% do the following:
SYS "ReadFile", @hfile%(file%), struct{}, DIM(struct{}), ^temp%, 0
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.