二进制文件两次写入数据

问题描述 投票:0回答:1

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

  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
1个回答
1
投票

打开文件时,您需要传递ios::trunc。这将导致文件内容被删除。这不会自动发生。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.