【发布时间】:2016-01-12 01:19:15
【问题描述】:
我正在尝试打开一个二进制文件以向其中写入一个整数并从中读取整数。但是每当我运行代码时,文件都不会打开。这是我的代码:
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();
【问题讨论】:
-
我看到你在寻找、写入和关闭文件。但我没有看到你明确打开文件......我不认为
is_open实际上打开了文件。我从online reference 看到构造函数应该打开文件,但显然在你的情况下它没有打开它,是吗?能否也提供运行程序时打印的输出? -
感谢@Pete Becker。我自己也发现了 :)
-
除了任何打印输出之外,您还可以粘贴所有代码吗?例如,我没有看到您的
#include <fstream>(请参阅在线参考中的示例)。 -
您似乎在使用
score_file.is_open()来检查文件是否已经存在。但如果是false,并不代表该文件不存在。这意味着您无法打开它,也无法对其进行写入/读取。一个原因可能是您没有读取/写入文件的权限。据我所知fstream会在文件不存在时创建该文件。