简体   繁体   English

二进制文件两次写入数据

[英]binary file writes data twice

I have the code for binary file handling.我有二进制文件处理的代码。

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

The above program is writing the last entered record twice, How do I stop the program writing the data twice to the binary file上面的程序将上次输入的记录写入两次,如何停止程序将数据两次写入二进制文件

You need to pass ios::trunc when opening the file.打开文件时需要通过ios::trunc This will cause the contents of the file to be deleted.这将导致文件的内容被删除。 This does NOT happen automatically.这不会自动发生。

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

What's currently happening is that you are opening an existing file containing two (I assume) items, overwriting the first item, then closing the file.当前发生的是您正在打开一个包含两个(我假设)项目的现有文件,覆盖第一个项目,然后关闭文件。 The second item is there because it was written by a previous run of your code.第二项在那里,因为它是由您的代码的先前运行编写的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM