Hi,
I'm trying to create a little database structure in GLBASIC using a DAT file.
I have the following type:
type record
ID
posx
posy
speed
endtype
I would like to write and read each type record into a dat file (write and recover). Finally, I would like to be able to do a seek for an specific record avoiding secuential access and using random access or similar.
Has GLBasic a way to do that or is it needed to use C++ inline? I don't need a complex structure (with sort and so on) only a more efficient way to write and read records using types and file commands.
Thanks in advance.
Best regards.
Make sure that your Type data is accessible in a GLOBAL manner.
(pseudocode - at work without GLB access, so from my poor memory)
GLOBAL rec[] as Trecord
Then use something like -
TYPE Trecord
ID
posx
posy
speed
ENDTYPE
...
...
...
FUNCTION save_data:
file$="blahblah.dat"
ok=DOESFILEEXIST file$
FILEOPEN (1,file$,FALSE)
FOREACH r in rec[]
WRITEWORD 1,r. ID
WRITEWORD 1,r.posx
WRITEWORD 1,r.posy
WRITEWORD 1,r.speed
NEXT
CLOSEFILE 1
ENDFUNCTION
That will save your TYPE data in sequences of ID,posx,posy,speed, ID,posx,posy,speed....
Then you do the opposite with READWORD to load in your data. Look up READWORD, READBYTE etc. in the Help file.
All of this code is incredibly fast and you can then sort it and locate data in an instant if you know what you are looking for.
for reading, see FILESEEK command.
Thank you very much for both posts! It was very clear :)
A "SERIALIZETYPE" command or sth. else would be awesome!!!
I asked a few months ago :)
What do you think Gernot?
I think that everything we can do ourselves in GLBasic as it is now, should be made by us. Let Gernot concentrate on new things that we can't do in GLBasic with built in commands. Like new target platforms, new sound system... I'm sure he doesn't need to look around for things to do when he is off work. :-)
Serialize your type structures is work yes but it's fully possible to do in GLBasic as it is now.
Yes sure,
but if you have 25 TYPES (for e.g. different objects) and you want to save and load them in runtime you have to write 25 functions for that (or not?)... Serializing a TYPE as xml/binary file is not too hard to implement, i think.
But it's not high priority... Other Features are more important. :P
problem with serialization is - how to make one version of the code compatible with another one?
Answer might be json or xml, but that would bloat the code dramatically, because every member of a type would need a 4-byte pointer to the variable's name as well now. You don't want a 2D point (2 ints) have the doulbe memory use just because you're too lazy to write an serialization function ;)
ok ok, you're right. :D