Save/Read struct to/from File
-
I have to save multiple pairs of (QPointF, Int) in a file and need to read them again.
This is my idea right now:
typedef pair<QPointF,int> vertex_info; struct graph_info{ QList<vertex_info> all_vertices; }; void MainWindow::on_button_save_clicked(){ QString s = this->ui->lineEdit->text(); this->ui->lineEdit->clear(); struct graph_info my_graph; vmap::iterator itr = myLogic->set.begin(); while(itr != myLogic->set.end()){ v = itr->second; my_graph.all_vertices.append(vertex_info(v->pos,v->type)); itr++; } QFile new_graph(s); new_graph.open(QIODevic::WriteOnly); }
How to save/read my struct properly?
-
Hi,
I suggest to create
QDataStream::operator<<()
andQDataStream::operator>>()
for your structureQDataStream& operator<<(QDataStream& stream, const graph_info& info) { ... } QDataStream& operator>>(QDataStream& stream, graph_info& info) { ... }
In that case you can save your data
QFile file("file.dat"); file.open(QIODevice::WriteOnly); QDataStream out(&file); // we will serialize the data into the file out << my_graph;
and read
QFile file("file.dat"); file.open(QIODevice::ReadOnly); QDataStream in(&file); // read the data serialized from the file in >> my_graph;
UPDATE: a complete different approach is to save your data in text format (for example JSON). Here you'll find a great example
-
thx for the fast answer, but how does the inside of these QDataStream declarations look like?
And what happens exactly in line:
in >> my_graph;
The Stream "in" looks into the file "file.dat" and reads it.
Sry i am kind of new but a task at my University forces me to find an answer to this problem :/
-
Hi,
you have to implements the
<<
and>>
operators for your struct.
Read the QDataStream Documentation to understand how implement them -
I came to this point:
struct vertex_info{ QPointF pos; int type; }; struct graph_info{ QList<vertex_info> all_vertices; }; QDataStream &operator<<(QDataStream &out, const vertex_info &v){ out << v.pos << v.type; return out; } QDataStream &operator<<(QDataStream &out, const graph_info &g){ int n = g.all_vertices.size(); for(int i=0; i<n ;i++){ out<<g.all_vertices.at(i); } return out; } QDataStream &operator>>(QDataStream &in, graph_info &g){ QList<vertex_info> L; return in; } QDataStream &operator>>(QDataStream &in, vertex_info &v){ return in; } void MainWindow::on_button_save_clicked(){ QString s = this->ui->lineEdit->text(); this->ui->lineEdit->clear(); vmap::iterator itr = myLogic->set.begin(); graph_info my_graph = new graph_info(); vertex_info vinfo; while(itr != myLogic->set.end()){ vinfo.first = itr->second->pos; vinfo.second = itr->second->type; my_graph.all_vertices.append(vinfo); itr++; } QFile file(s); file.open(QIODevice::WriteOnly); QDataStream stream(&file); stream << my_graph; file.close(); }
Any suggestions or solutions? :/
-
Anyone? :/
-
Hi,
you have to decide the format of your file; we got you information how to use properly the QT classes but you should thing about the format.