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

标签 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

所以我尝试从我已有的二进制文件进行更新。但它无法获得新的高分并给我审查,请告诉我哪里错了以及如何解决,谢谢! (我不是英语,如果我的英语不好,我很抱歉)

最佳答案

这一点显然是错误的(假设你真的想要排序的值):

//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 位的。

关于c++ - 使用二进制文件进行简单的高分更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24593097/

相关文章:

C++将高分辨率时钟与固定数字进行比较

c++ - 无法将 FindFileData.cFileName 转换为字符串

Python3 (v3.2.2) 写入二进制文件时的额外位

c++ - C++ 二进制文件读取性能

java - ObjectInputStream.readobject() 在异常中抛出对象

c++ - OSX 终端中的鼠标位置/控制

c++ - 唯一的指针类初始化

c++ - 模板类的模板化构造函数的显式实例化

c# - C# 中二进制文件的读写

c - 如何在二进制文件中写入指针? (C)