读取结构化二进制文件c++
read structured binary file c++
你好,我刚刚编写了以下程序,通过输入一些信息并在控制台中显示它来创建一个.dat文件。但在用户提示程序崩溃后打印"显示记录";我确信读取函数(ItemFile.read(reinterpret_cast
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
是一种选择)。
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 如何忽略某些二进制文件的执行?
- 对在不同二进制文件中创建的对象文件的依赖关系
- 我的 SDL2 程序需要哪些二进制文件,以便它在另一台未安装 SDL2 的计算机中工作