0
我對使用流和處理FileWriter有點新。 這是我得到通過搜索實例/解決方案:向/從文件寫入/讀取結構
struct vertex_info{
QPointF pos;
int type;
};
struct graph_info{
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 = sizeof(g.all_vertices);
for(int i=0; i<n ;i++){
out<<g.all_vertices[i];
}
return out;
}
QDataStream &operator>>(QDataStream &in, graph_info &g){
//vertex_info vertex_array[];
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;
vertex_info vinfo;
int i = 0;
while(itr != myLogic->set.end()){
vinfo.pos = itr->second->pos;
vinfo.type = itr->second->type;
my_graph.all_vertices[i] = vinfo;
itr++;
i++;
}
QFile file("test.dat");
file.open(QIODevice::WriteOnly);
QDataStream stream(&file);
stream << my_graph;
file.close();
}
void MainWindow::on_button_load_clicked(){
this->on_button_clear_clicked();
graph_info my_graph;
QString s = this->ui->box_select_graph->currentText();
QFile file("test.dat");
file.open(QIODevice::ReadOnly);
QDataStream in(&file);
in >> my_graph;
int i=0;
while(i<sizeof(my_graph.all_vertices)){
QString posx = QString::number(my_graph.all_vertices[i].pos.x());
QString posy = QString::number(my_graph.all_vertices[i].pos.y());
QString type = QString::number(my_graph.all_vertices[i].type);
cout<<posx<<" "<<posy<<" "<<type<<'\n';
}
}
所以我還是didnt實現在兩種結構流,因爲我真的不知道它是如何工作的。
任何建議/解決方案? :/
閱讀更多關於[序列化](https://en.wikipedia.org/wiki/Serialization)。對於複雜的數據結構,使用文本格式是值得實用的,例如[JSON](http://json.org/) –