使用二进制文件进行简单的高分更新

时间:2014-07-06 05:51:06

标签: c++ binaryfiles

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
//#define DEBUG
int main()
{

#ifndef DEBUG
int new_highscore;
cout << "Enter your new highscore: ";
cin >> new_highscore; //input 5
#endif

fstream file("bin_file.dat", ios::binary | ios::in | ios::out); //file already had 10 6 4

#ifdef DEBUG
int x = 0;
while (file.read(reinterpret_cast<char*>(&x), sizeof(x)))
cout << x << " ";
#endif

#ifndef DEBUG
if (file.is_open())
{
    streampos pre_pos = ios::beg;
    int cur_score = 0;
    vector <int> scores;

    while (file.read(reinterpret_cast<char*>(&cur_score), sizeof(cur_score)))
    {
        if (cur_score < new_highscore)
        {
            break;
        }
        pre_pos = file.tellg();
    }

    if (file.fail() && !file.eof())
    {
        cout << "Error! Exiting..." << endl;
        return 0;
    }

    file.clear();
    file.seekg(pre_pos);

    //get all scores that lesser than new high scores into vector
    while (file.read(reinterpret_cast<char*>(&cur_score), sizeof(cur_score)))
        scores.push_back(cur_score);

    //put new high score into right position 
    //edit
    file.seekp(pre_pos);
    file.write(reinterpret_cast<char*>(&new_highscore), sizeof(new_highscore));

    //put all the scores that lesser than new high score into file
    for (vector<int>::iterator it = scores.begin(); it != scores.end(); it++)
        file.write(reinterpret_cast<char*>(&*it), sizeof(*it));
    file.clear();
}
else
    cout << "Error openning file! " << endl;

//Try to print to console the result for checking
cout << "Review:" << endl;
file.seekg(0, ios::beg);
int temp = 0;

while (file.read(reinterpret_cast<char*>(temp), sizeof (temp))) //Error here, and can't write 5 to the file
    cout << temp << endl;
#endif
file.close();
return 0;
}

代码链接:http://ideone.com/pC2ngX

所以我试图从我已经拥有的二进制文件更新。但是它无法获得新的高分并将其评论给我,请让我在哪里出错,以及如何解决它,谢谢!! (如果我的英语不合适,我不是英语,很抱歉)

1 个答案:

答案 0 :(得分:2)

这一点显然是错误的(假设您确实希望对值进行排序):

//put new high score into last position in file
file.seekp(0, ios::end);
file.write(reinterpret_cast<char*>(&new_highscore), sizeof(new_highscore));

因为您将值放在最后,而不是在计算值的位置(pre_pos)。

这可以更简单:

for (vector<int>::iterator it = scores.begin(); it != scores.end(); it++)
    file.write(reinterpret_cast<char*>(&*it), sizeof(*it));

为:

file.write(reinterpret_cast<char*>(scores.data()), sizeof(scores[0]) * scores.size());

通常,我只是将文件读入一个向量,将新值插入内存中的正确位置,然后将其写回。唯一可能不起作用的情况是,如果您的高分表超过2-3GB且您的OS / App是32位。