简体   繁体   中英

Write/Read Struct To/From File

I am kind of new to using streams and handling 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.

Any suggestions/solutions? :/

First off, I assume you're using C++ here. So in struct graph_info you're going to want

std::vector<vertex_info> all_vertices;

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

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.

Once you've done that you'll be in a better place to start writing the >> operators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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