PDA

View Full Version : Read binary file into 2 QVectors



juracist
17th May 2012, 17:46
Hello, I have one question about reading binary files.

I wrote data like this:


QVector<QPoint> p;

QFile binfile(path);
binfile.open(QIODevice::WriteOnly);
QDataStream out(&binfile);

out << p;



..and tried reading it this way:



QFile bin(fileName);
bin.open(QIODevice::ReadOnly);
QDataStream in(&bin);


QVector<qint32> x, y;

in >> x >>y;



I know this isn't the right way to read this kind of data,
so can anyone help me to put binary data into two vectors, x and y.

Data is written into binary file as a list of points: x1 y1 x2 y2 x3 y3..
..and i should read first all x coordinates to x vector and all y coordinates to y vector..

amleto
17th May 2012, 19:15
you stored it as a QPoint so you must read it back as a QPoint! :)



QFile bin(fileName);
bin.open(QIODevice::ReadOnly);
QDataStream in(&bin);

QVector<QPoint> points;
QVector<qint32> x, y;

QPoint p;
in >> p;
x << p.x();
y << p.y();

juracist
17th May 2012, 19:37
Thanks, i did it your way , except, last two lines (it didn't work for me :S):


.......
for(int i=0;i<p.size();i++){
x.append(p.at(i).x());
y.append(p.at(i).y());
}


..but now this looks primitive and i think it can be done a lot shorter and faster..

amleto
17th May 2012, 19:46
QFile bin(fileName);
bin.open(QIODevice::ReadOnly);
QDataStream in(&bin);

QVector<qint32> x, y;

QPoint p;
while (!in.atEnd())
{
in >> p;
x.push_back(p.x());
y.push_back(p.y());
}

ChrisW67
18th May 2012, 05:59
If you already have the vector of points in memory why aren't you just using them as-is? Seems you are writing a file only to transform the data.

juracist
19th May 2012, 16:17
Firstly, I parse xml file and after calculating points for plotting graph, i save those points to binary file so it can be easier to load them later without parsing xml again.
Problem is, that data can be added to plotting function as two vectors of doubles, one vector for x, other for y coordinate.

This is the function i use: void QCPGraph::addData ( const QVector< double > & keys, const QVector< double > & values ) (http://www.workslikeclockwork.com/other/qcustomplot-doc/classQCPGraph.html#aa5c6181d84db72ce4dbe9dc15a34ef 4f) from QCustomPlot library

amleto
20th May 2012, 00:35
so parse the file into memory in convenient format - and KEEP it in memory. File access is very slow!