PDA

View Full Version : Function for repositioning the file pointer



psantofe
8th September 2010, 15:46
In my app I have to save data in an external binary file (I choose QDataStream class); in particular, I have array of 20 items arranged in 100 memories. Like a bidimensional array, in which I would write o read data starting not necessarily from the begin of file.
The following is the Read() function I'm developing:

void prova12::Read()
{
QString miodato[230]; // array based on QString class
QFile DataStore("store.dat"); // the external binary file to be read is: store.dat
DataStore.open(QIODevice::ReadOnly; // file open in readonly mode
QDataStream in(&DataStore); // datastream is read
for(index = 0; index < 230; index++)
in >> miodato[index]; // the first 230 data in store.dat are saved in "miodato" array
}

From the Qt help, I found:
bool QIODevice::seek(qint64 pos)
It seems to be the solution to my problem, when I want to start my reading from 3rd data; the following is my trial:

void prova12::Read()
{
QString miodato[230];
QFile DataStore("store.dat");
DataStore.open(QIODevice::ReadOnly);
QDataStream in(&DataStore);
/****************/
DataStore.seek(3); // Start to read from 3rd data
/****************/
for(index = 0; index < 230; index++)
in >> miodato[index];
}

But, unfortunately, it doesn't work.
Is there anybody that already use these instructions or understand what's my error?
Thanks
Paolo

wysota
8th September 2010, 15:49
How does "doesn't work" manifest itself?

Dan Milburn
8th September 2010, 20:36
Your code would work if the strings start at the third byte in the file. I suspect what you're actually trying to do is start reading from the third string that was written, which will not work and cannot be done with QDataStream, but it's not entirely clear. Further information about how your data is being written would be useful.

psantofe
9th September 2010, 08:19
@Dan
Yes you're right; I'm trying to read starting from my third string and not from the third byte.
Is it possible to to this in your opinion?
Thanks
Paolo

wysota
9th September 2010, 08:58
You have to read from the beginning as you don't know how long each string is. Alternatively use an sqlite database file, then you'll have records and will be able to jump to each record immediately.

tbscope
9th September 2010, 09:03
Or a structured file like an xml file

wysota
9th September 2010, 10:41
Or a structured file like an xml file

Technically speaking with an xml file he'll still have to read the file from the beginning :)

psantofe
9th September 2010, 13:36
Solved!
The Qdatastream.seek() function works perfectly if I set the pointer correctly; as my array elements are QString based, I've to look for the initial byte of 3rd string (so number is not "3" but depends on the String lenght).
Thank you to all for your anwser.
Paolo