C++ Read and write multiple objects of same class

前端 未结 4 832
故里飘歌
故里飘歌 2021-01-13 06:52
airport air(1,2,3); //an airport constructor
ofstream myfile;
myfile.open(\"rishab\",ios::app||ios::binary);
myfile.write((char*)air,sizeof(airport);
myfile.close();         


        
4条回答
  •  -上瘾入骨i
    2021-01-13 07:42

    You can program it like this.

    struct AirPort
    {
        int a;
        int b;
        int c;
    };
    int main()
    {
        std::vector airportList;
        FILE* fp = fopen(filename,"rb");
        if( NULL != fp)
        {
            while(!feof(fp))
            {
                AirPort ap;
                if (fread(&ap,sizeof(ap),1,fp)==1)
                {
                    airportList.push_back(ap);
                }
            }
        }
        fclose(fp);
        return 0;
    }
    

提交回复
热议问题