从文件写入和读取数据时丢失数据(随机访问文件,C ++)

时间:2014-02-10 11:53:11

标签: c++ file fstream random-access randomaccessfile

首先,我通过编写以下数据初始化“hardware.dat”文件,然后以列表形式显示它们。 enter image description here enter image description here

然而,当我处理选择2然后退出选择2而不编辑或添加任何内容时,所有数据都会丢失。我建议任何事情都不会改变。 enter image description here

为什么存在问题?如何解决?

感谢您的关注。


代码:

int question_3()
{
    cout << "Question 3" << endl;
    create_One_Hundred_blank_Data();
    char choice = '0';
    do
    {
    cout << "---------------Main Menu---------------" << endl
         << "1. Initialize hardware data." << endl
         << "2. Add / Edit data." << endl
         << "3. Remove data." << endl
         << "4. Show whole data in the file." << endl;
    cout << "Enter choice > ";      choice = getch();       cout << choice << endl;     // #include <conio.h>
    switch_Choice(choice);
    }while (choice != '0');

    cout << "Program is ended." << endl;
    return 0;
}


void switch_Choice(char choice)
{
    switch (choice)
    {
        case '1':
            choice_1();
            break;

        case '2':
            choice_2();
            break;

        case '3':
            choice_3();
            break;

        case '4':
            choice_4();
            break;
    }
}



void choice_2()
{
    hardware.open("hardware.dat", ios::binary | ios::out);
    if (!hardware)
    {
        cerr << "File could not be opened." << endl;
        exit(1);
    }

    int record = 0;
    string tool_name = "";
    int quantity = 0;
    int cost = 0;
    string buffer_Eater = "";

        cout << "Enter record number <O to exit input> : ";     cin >> record;
    while(record != 0)
    {
        cout << "Enter tool name                       : ";     getline(cin, tool_name); getline(cin, buffer_Eater);
        cout << "Enter quantity                        : ";     cin >> quantity;
        cout << "Enter cost                            : ";     cin >> cost; 

        write_Single_Data(myHardwareData, record, tool_name, quantity, cost);

        cout << "Enter record number <O to exit input> : ";     cin >> record;
    }
    hardware.close();
    output_Whole_File_Data();
    separation_line();
}



void output_Whole_File_Data()
{
    hardware.open("hardware.dat", ios::binary | ios::in);
    output_Data_LineHead();
    hardware.read(reinterpret_cast<char *>(&myHardwareData), sizeof(HardwareData));
    int counter = 0;
    cout << setprecision(2) << fixed;
    while (hardware && !hardware.eof())
    {
        if (myHardwareData.getRecord() != 0)
            output_Data_Line(cout, myHardwareData);

        hardware.read(reinterpret_cast<char *>(&myHardwareData), sizeof(HardwareData));
    }
    hardware.close();
}

1 个答案:

答案 0 :(得分:1)

尝试替换

hardware.open("hardware.dat", ios::binary | ios::out);

通过

hardware.open("hardware.dat", ios::binary | ios::out | ios::app);