正在打开二进制文件
Opening binary file
本文关键字:二进制文件 更新时间:2023-10-16
我试图打开一个二进制文件,向其中写入一个整数,并从中读取整数。但每当我运行代码时,该文件都不会打开。这是我的代码:
int bufferScore; //temporary storage for score from file.
int gamePoints;
cout << "number: "; cin >> gamePoints;
fstream score_file("Score_file.bin", ios::binary | ios::in | ios::out);
if (score_file.is_open())
{
score_file.seekg(0);
score_file.read(reinterpret_cast<char *>(&bufferScore), sizeof(bufferScore));
if (gamePoints > bufferScore)
{
cout << "NEW HIGH SCORE: " << gamePoints << endl;
score_file.seekp(0);
score_file.write(reinterpret_cast<char *>(&gamePoints), sizeof(gamePoints));
}
else
{
cout << "GAME SCORE: " << gamePoints << endl;
cout << "HIGH SCORE: " << bufferScore << endl;
}
}
else
{
cout << "NEW HIGH SCORE: " << gamePoints << endl;
score_file.seekp(0);
score_file.write(reinterpret_cast<char *>(&gamePoints), sizeof(gamePoints));
}
score_file.close();
如果文件不存在,则必须再次尝试在没有std::ios::in
的情况下打开它
其次,您可以使用标准的c++io,而不是编写二进制数据。它稍微慢一点,但在不同的平台上更兼容。如果你不想让程序修改新行等,你仍然可以使用ios::binary
标志。
std::string filename = "Score_file.bin";
std::fstream file(filename, std::ios::in | std::ios::out | std::ios::binary);
if (!file)
{
cout << "create new filen";
file.open(filename, std::ios::out | std::ios::binary);
if (!file)
{
cout << "permission denied...n";
return 0;
}
}
cout << "read existing file...n";
int i = 0;
while(file >> i)
cout << "reading number: " << i << "n";
//write new number at the end
file.clear();
file.seekp(0, std::ios::end);
file << 123 << "n";
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 如何忽略某些二进制文件的执行?
- 对在不同二进制文件中创建的对象文件的依赖关系
- 我的 SDL2 程序需要哪些二进制文件,以便它在另一台未安装 SDL2 的计算机中工作