简单的高分更新使用二进制文件
Simple high-score update using binary file
#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位的,那么这种方法可能就行不通了。
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 无法正确编写和更新二进制文件
- 从二进制文件C++更新数据
- 如何编写自我替换/更新二进制文件
- 在运行时动态更新二进制文件(可执行文件)而不停止的任何类型的方法
- 如何在二进制文件(.net或非托管文件)中注入/更新Version和其他详细信息
- 简单的高分更新使用二进制文件
- 用c++更新二进制文件中的记录
- 更新二进制文件中的学生记录,同时删除以前的数据
- 二进制文件在C++中更新
- 需要帮助调试简单的更新二进制文件的功能