c++ - 二进制文件两次写入数据
问题描述
我有二进制文件处理的代码。
class info
{
public:
int pno, qty;
char pname[50];
float price;
void getdata()
{
cout << "Enter product number: "; cin >> pno;
cout << "Enter product name: "; cin >> pname;
cout << "Enter the price: "; cin >> price;
cout << "Enter the quantity: "; cin >> qty;
}
void display()
{
cout << "Product number: " << pno << endl;
cout << "Product name: " << pname << endl;
cout << "Price: " << price << endl;
cout << "Quantity Available: " << qty << endl;
cout << "\n";
}
};
void createfile()
{
info obj; char flag='y';
fstream fin("project.dat", ios::out|ios::binary);
cout << "Enter the values to be stored in the file" << endl;
while(flag=='y')
{
obj.getdata();
fin.write((char*)&obj ,sizeof(obj));
cout << "Data has been added to the file." << endl;
cout << "Do you want to continue adding more? : "; cin >> flag;
}
fin.close();
[![OUTPUT][1]][1] cout << "Proceeding to program..." << endl;
}
上面的程序正在两次写入最后输入的记录,如何停止程序两次将数据写入二进制文件
解决方案
ios::trunc
打开文件时需要通过。这将导致文件的内容被删除。这不会自动发生。
fstream fin("project.dat", ios::out|ios::binary|ios::trunc);
当前发生的是您正在打开一个包含两个(我假设)项目的现有文件,覆盖第一个项目,然后关闭文件。第二项在那里,因为它是由您的代码的先前运行编写的。
推荐阅读
- javascript - 有些东西阻止 addEventListener(type, handler) 在 DOM 中工作
- powershell - 无法在 Windows Server 上卸载 IoT Edge
- c++ - 如何使用 Visual Studio 2017 设置正确设置 PCL 库?
- python - 如何在python中保存使用exchangelib库生成的电子邮件消息项
- html - 在 iPadOS 13 中更改 URL 时如何在 Web 应用程序中保持全屏显示
- r - 使用函数参数并将其传递给 lm 公式
- css - 在 Angular 中为组件添加自定义样式
- php - 多个可选参数排序问题
- azure - 使用通用 Git 连接时,是否可以为 Azure Pipelines 使用自定义 docker 映像?
- ios - CoreData 子上下文在第二次保存后不会将更改推送到父级