gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:44:34 25 4
gpt4 key购买 nike

您好,我刚刚编写了以下程序,通过输入一些信息并在控制台中显示来创建一个 .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() 成员函数)并将它们写入文件而不是 字符串对象。此外,请注意可移植性问题,例如 int 等多字节类型(可以选择 uint32_t 等固定宽度整数),如果您的程序旨在在不同平台上运行。

关于c++ - 读取结构化二进制文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25171895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com