Why not use random access files?

Posted by Orioneyes on Sat 17 Jun 2006 03:01 AM — 3 posts, 11,691 views.

#0
I run a SWR mud and noticed the file opening methods on all of them anew now that I've been learning C. I found out about random access files, and I've been wondering about them.

Why are all the files saved as text files instead of binaries? Is there some inherent flaw in this file type, or perhaps something special about the codebase I should know in relation to this file type? Just to let you know what I mean..

/* Vector structure */
struct vector
{
int x;
int y;
int z;
};
int main ()
{
struct vector vect;

/* We skip to record 6, for example */
fp = fopen("myFile.dat", "rb+");

/* We know the exact spot in the file using this formula */
fseek( fp, 5 * sizeof(struct vector), SEEK_SET );

/* At our position we read in the data en masse */
fread( &vect, sizeof( struct vect ), 1, fp );

printf("X: %d Y: %d Z: %d\n", vect.x, vect.y, vect.z );
fclose(fp);
return 0;
}

The code requires that you create a binary file before you can use it, but then again you can have a default size of 100 records and increase it whenever its 3/4 of the way full, for instance. Does anyone know why this isn't done?
Australia Forum Administrator #1
It's just a lot less flexible, that's why. On modern computers the speed and size of text files is hardly an issue. In your example if you wanted to add another field (int w for example) then the structure size changes, and the old data can no longer be accessed.


Also it doesn't lend itself to strings very well. For fixed-length records you need to allocate the longest possible size for a string, so what would you allow for a room description for instance? 1000 characters? Even then it would be too small for a few cases, and much too large for most of them, which is very wasteful.

It would also be tedious in the extreme to edit such a file "by hand" with a text editor to make corrections outside the program.

In fact, modern technique is to not only use text, but with named fields, so they are more easily expanded later, for example, XML, or things like Lua serialised data. For example:


roomname = "West Wing"
roomdesc = "You are standing within the expanse of the famous Darkhaven Square."

#2
makes sense. Thanks Nick :)