无法正确编写和更新二进制文件

时间:2017-04-18 17:31:07

标签: c++ binary

我可以选择要更新的记录,包括要更改的学生ID以及名称。但是,当我选择查看我的二进制文件时,它最终不会记录到二进制文件中 - 所有记录最终都保持不变。请指教!

最好,MM

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <cstring>
using namespace std;

const int MAX = 100;

struct student
{
    int identity;
    char name[MAX];
    int notask;
    int atask[MAX];
    int finalmark; 
};


void updateRecord (fstream& bfilem1, const char bfilenamem1[])
{
    char updateRecord;
    int k;
    student s;

    bfilem1.open(bfilenamem1, ios::in | ios::out | ios::binary);

    if (!bfilem1)
    {
        cout << "Updating of binary " << bfilenamem1 
             << " has failed" << endl;
        bfilem1.close();
    }

    int i=1;

    cout << "Begin updating of binary file " << bfilenamem1;
    cout << endl;
    cout << "Information for student file" << endl;
    cout << endl;

    while (bfilem1.read (reinterpret_cast <char *>(&s), sizeof (s)))
    {
        cout << i << "\t"
             << s.identity << " "
             << s.name << endl;
        i++;
    }

    bfilem1.seekg(0, ios::beg);

    do 
    {   
        cout << "Update record: ";
        cin >> k;
        cout << endl;

        // Take out record
        bfilem1.seekg ((k - 1) * sizeof (student), ios::beg);
        bfilem1.read (reinterpret_cast <char *>(&s), sizeof (s));        

        // Update record
        cout << "Student ID: ";
        cin >> s.identity;
        cin.clear();
        cin.ignore();
        cout << "Update the name: ";
        cin.getline(s.name, MAX);

        // Put back record
        bfilem1.seekp ((k - 1) * sizeof (student), ios::beg);
        bfilem1.write (reinterpret_cast <const char *>(&s), sizeof (s));

        cout << "Student ID " << s.identity << " updated" << endl;
        cout << "Any more update (y/n): ";
        cin >> updateRecord;
        cout << endl;

    } while ((updateRecord=='y')||(updateRecord=='Y'));

    // Close bfile
    bfilem1.close();
}

1 个答案:

答案 0 :(得分:1)

有时当我们使用二进制文件或文本文件时,使用指针可能会给我们带来不好的打法,尝试关闭文件并在使用anoter指针(seekg或seekp)之前再次打开它。在搜索文件中的记录之前检查k <= 0 || k&gt; = i的情况

// Update record
    cout << "Student ID: ";
    cin >> s.identity;
    cin.clear();
    cin.ignore();
    cout << "Update the name: ";
    cin.getline(s.name, MAX);
    bfilem1.close();
    bfilem1.open(bfilenamem1, ios::in | ios::out | ios::binary);

    // Put back record
    bfilem1.seekp((k - 1) * sizeof(student), ios::beg);
    bfilem1.write(reinterpret_cast <const char *>(&s), sizeof(s));