读取结构化二进制文件c++

read structured binary file c++

本文关键字:c++ 二进制文件 结构化 读取      更新时间:2023-10-16

你好,我刚刚编写了以下程序,通过输入一些信息并在控制台中显示它来创建一个.dat文件。但在用户提示程序崩溃后打印"显示记录";我确信读取函数(ItemFile.read(reinterpret_cast(&Item),sizeof(Item))是错误的,但我被卡住了。谢谢你的帮助。

 struct fileOperation
 {
      string ItemDescription;
      int QuantityAtHand;
      float WholeSaleCost;
      float RetailCost;
      int DateAddedtoInventory;
 };
 void DisplayFiles(fileOperation,fstream);
 fileOperation writtenFileInformation(fileOperation);
 fileOperation writtenFileInformation(fileOperation Item)
 {
    cout<<"Please enter inventory description "<<endl;
    cin>>Item.ItemDescription;
    cout<<"Please enter Quantity description "<<endl;
    cin>>Item.QuantityAtHand;
    cout<<"Please enter the whole sale cost "<<endl;
    cin>>Item.WholeSaleCost;
    cout<<"Please enter the retail sale cost"<<endl;
    cin>>Item.RetailCost;
    cout<<"DataAddedtoInventory "<<endl;
    cin>>Item.DateAddedtoInventory;
    return Item;
}
 int main()
 {
   fileOperation Item;
   fileOperation newObject;
   fileOperation Item1;
   int button;
   bool flag;
   flag=true;
   cout<<"This program perform following operations :"<<endl;
   cout<<"Add new records to the file .(press 1)"<<endl;
   cout<<"Displahy new records to the file .(press 2)"<<endl;
   cout<<"Change any Record to the file (press3)"<<endl;
   fstream ItemFile("inventory1.dat",ios::in|ios::out|ios::binary);
   cin>>button;
   if(button==1)
   {
     while(flag)
     {
        newObject=writtenFileInformation(Item);
        cout<<"you have :";
        ItemFile.write(reinterpret_cast<char *>(&Item),sizeof(Item));
        cout<<"Do you wish to continue"<<endl;
        cin>>button;
        if(button!=1)
        {
            flag=false;
        }
        ItemFile.close();
    }
}
else if(button==2)
{
    cout<<"DisplayRecords "<<endl;
    if(!ItemFile)
    {
        cout<<"Error opening file.program aborting.n";
        return 0;
    }
    ItemFile.read(reinterpret_cast<char *>(&Item),sizeof(Item));
    while(!ItemFile.eof())
    {
        cout<<"Item description is: "<<Item.ItemDescription<<endl;
        cout<<"Quantity at hand is: "<<Item.QuantityAtHand<<endl;
        cout<<"Whole sale cost is: $"<<Item.WholeSaleCost<<endl;
        cout<<"Retail sale cost is: $"<<Item.RetailCost<<endl;
        cout<<"the data this have been added is "<<Item.DateAddedtoInventory<<endl;
        ItemFile.read(reinterpret_cast<char *>(&Item),sizeof(Item));
     }
    ItemFile.close();
}
}
ItemFile.write(reinterpret_cast<char *>(&Item),sizeof(Item));
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is wrong

如果对象包含std::string对象,则不能直接逐个字节地持久化对象。它可能会维护一个内部指针,指向堆上动态分配的缓冲区(您的字符串数据实际上存储在那里),该指针可能在重新加载后悬垂。

您可以做的一件事是显式地抓取数据(使用c_str()data()成员函数)并将它们写入文件而不是string对象。此外,如果您的程序打算在不同的平台上运行,请注意可移植性问题,如端序,数据大小等多字节类型,如int(固定宽度整数,如uint32_t是一种选择)。