首页 > 解决方案 > 二进制文件两次写入数据

问题描述

我有二进制文件处理的代码。

  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;
}

上面的程序正在两次写入最后输入的记录,如何停止程序两次将数据写入二进制文件

标签: c++binaryfiles

解决方案


ios::trunc打开文件时需要通过。这将导致文件的内容被删除。这不会自动发生。

fstream fin("project.dat", ios::out|ios::binary|ios::trunc);

当前发生的是您正在打开一个包含两个(我假设)项目的现有文件,覆盖第一个项目,然后关闭文件。第二项在那里,因为它是由您的代码的先前运行编写的。


推荐阅读