So, you need (de)serialization.
Try to do it right. Here is official documentation: http://qt-project.org/doc/qt-4.8/datastreamformat.html Here is example: Serialization with Qt
Question
After readLine()
, how to set cursor position to the beggining of a line?
Using seek()
and pos()
doesnt work for me.
Here is how my file.txt look like:
Object1 Some-name 2 3.40 1.50
Object2 Some-name 2 3.40 1.50 3.25
Object3 Some-name 2 3.40 1.50
Here's my code:
QFile file("file.txt");
if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&file);
while(!stream.atEnd()) {
qint64 posBefore = file.pos();
QString line = stream.readLine();
QStringList splitline = line.split(" ");
if(splitline.at(0) == "Object1") {
stream.seek(posBefore);
object1 tmp;
stream >> tmp;
tab.push_back(tmp);
}
if(splitline.at(0) == "Object2") {
stream.seek(posBefore);
object2 tmp;
stream >> tmp;
tab.push_back(tmp);
}
if(splitline.at(0) == "Object3") {
stream.seek(posBefore);
object3 tmp;
stream >> tmp;
tab.push_back(tmp);
}
}
file.close();
}
La solution
So, you need (de)serialization.
Try to do it right. Here is official documentation: http://qt-project.org/doc/qt-4.8/datastreamformat.html Here is example: Serialization with Qt
Autres conseils
I've made a simple console app for you. All you need to do is a good old QString::split()
by spaces and take the first element in the row however you like, i did it via QString::section()
method.
Well here is the code for main.cpp:
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QStringList>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile f("file.txt");
f.open(QIODevice::ReadOnly);
// next line reads all file, splits it by newline character and iterates through it
foreach (QString i,QString(f.readAll()).split(QRegExp("[\r\n]"),QString::SkipEmptyParts)){
QString name=i.section(" ",0,0);
// we take first section of string from the file, all strings are stored in "i" variable
qDebug()<<"read new object - "<<name;
}
f.close();
return a.exec();
}
File file.txt is in the same directory as the executable file and is copy of your file:
Object1 Some-name 2 3.40 1.50
Object2 Some-name 2 3.40 1.50 3.25
Object3 Some-name 2 3.40 1.50