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 **** and ****, 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:

code format="bb4w" SYS "WriteFile", @hfile%(file%), struct{}, DIM(struct{}), ^temp%, 0 code Similarly to read an entire structure **struct{}** from the file opened on channel **file%** do the following:

code format="bb4w" SYS "ReadFile", @hfile%(file%), struct{}, DIM(struct{}), ^temp%, 0 code 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:

code format="bb4w" 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 code

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.