2015-06-16 163 views
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实现在两种结构流,因为我真的不知道它是如何工作的。

任何建议/解决方案? :/

+0

阅读更多关于[序列化](https://en.wikipedia.org/wiki/Serialization)。对于复杂的数据结构,使用文本格式是值得实用的,例如[JSON](http://json.org/) –

回答

0

首先,我假设你在这里使用C++。因此,在struct graph_info你会想

std::vector<vertex_info> all_vertices; 

然后在QDataStream &operator<<你会想

size_t n = g.all_vertices.size(); 
QDataStream &operator<<

而且你可能会想要写顶点数量出去该流,以便读者能够首先阅读,知道有多少人阅读。

一旦你这样做了,你将会在更好的地方开始编写>>运营商。

+0

Thx用于快速回答,是它的C++。所以现在我用一个矢量而不是一个List或一个数组,但我仍然不知道如何实现这些插槽。某处有一个非常简单的例子吗? – droelf