简体   繁体   English

向文件写结构/从文件读结构

[英]Write/Read Struct To/From File

I am kind of new to using streams and handling FileWriter. 我是使用流和处理FileWriter的新手。 This is what i got by searching for examples/solutions: 这是我通过搜索示例/解决方案得到的:

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';
    }
}

So I still didnt implement the in streams for both structs, since i dont really know how it works. 所以我仍然没有为两个结构实现in流,因为我真的不知道它是如何工作的。

Any suggestions/solutions? 有什么建议/解决方案吗? :/ :/

First off, I assume you're using C++ here. 首先,我假设您在这里使用C ++。 So in struct graph_info you're going to want 因此,在struct graph_info您将想要

std::vector<vertex_info> all_vertices;

Then in QDataStream &operator<< you're going to want 然后在QDataStream &operator<<

size_t n = g.all_vertices.size();

Also in QDataStream &operator<< you're probably going to want to write the number of vertices out to the stream, so that the reader will be able to read that first to know how many to read. 同样在QDataStream &operator<<您可能想要将顶点数量写出到流中,以便读者能够首先阅读该顶点,从而知道要阅读多少个顶点。

Once you've done that you'll be in a better place to start writing the >> operators. 完成后,您将可以在一个更好的地方开始编写>>运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM