tmighty
tmighty

Reputation: 11399

Data position in file

At first I loaded all my variables to memory at application start. Over time, the number of variables became so huge that I don't want to do that anymore. Instead I am retrieving them only when they are needed (using a mapped file, but that is another story).

At first I write the variables to a file. (this is repeated many times...)

vector<udtAudioInfo>::iterator it = nAudioInfos.Content().begin();
for (;it != nAudioInfos.Content().end(); ++it)

    //I think here I should store the position where the data will begin in the file
    //I still need to add code for that...

    //now write the variables 
    fwrite(&it->UnitID,sizeof(int),1,outfile);
    fwrite(&it->FloatVal,sizeof(double),1,outfile);

    //I think here I should store the length of the data written
    //I still need to add code for that...
 }

But now that I need to load the variables dynamically, I need to keep track of where they are actually stored.

My question would be: How can I find out the current write position? I think and hope that I could use this to keep track over where the data actually resides in the file.

Upvotes: 0

Views: 147

Answers (2)

Philip
Philip

Reputation: 281

I suggest you read all variables at once, maybe using a struct:

struct AppData
{
    udtAudioInfo audioInfos[1024];
    int infoCount;

    ... // other data
};

And then load/save it via:

AppData appData;
fread(appData, 1, sizeof(AppData), infile);
...
fwrite(appData, 1, sizeof(AppData), outfile);

Actually, this is going to be much faster than multiple read/write operations.

Upvotes: 0

Andy Thomas
Andy Thomas

Reputation: 86459

You can use the function ftell() as you are reading or writing the variables.

For example, in your example code above, you could find the position at the start of each iteration with:

 long fpos = ftell( outfile );

When you are ready to return to that position, you can use fseek(). (Below, SEEK_SET makes the position relative to the beginning of the file.)

 fseek ( infile, position, SEEK_SET );

Upvotes: 1

Related Questions