正在打开二进制文件

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";