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

Simple high-score update using binary file

本文关键字:二进制文件 更新 简单      更新时间:2023-10-16
#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

所以我试着从我已经有二进制文件更新。但是它无法得到新的高分并审查给我,请告诉我哪里出错了以及如何修复,谢谢!!(我不是英国人,很抱歉我的英语不好)

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

//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());

一般来说,我只需将文件读入vector,将新值插入内存中的正确位置,然后将其写回来。如果你的高分表超过2-3GB,并且你的操作系统/应用程序是32位的,那么这种方法可能就行不通了。