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

时间:2014-08-06 23:24:07

标签: c++

您好我刚刚编写了以下程序来创建.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();
}

}

1 个答案:

答案 0 :(得分:3)

ItemFile.write(reinterpret_cast<char *>(&Item),sizeof(Item));
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is wrong

如果对象包含std::string对象,则不能逐个字节地直接保留它。它可以维护一个内部指针,指向堆上的动态分配缓冲区(真正存储了你的字符串数据),重新加载后可能会悬空。

您可以做的一件事是明确地获取数据(使用c_str()data()成员函数)并将它们写入文件而不是string对象。另外,要注意像int这样的多字节类型的字节顺序,数据大小等可移植性问题(如uint32_t那样是固定宽度整数),如果你的程序是要运行的话不同的平台。