打开二进制文件

时间:2016-01-12 01:19:16

标签: c++ file binary

我正在尝试打开一个二进制文件来写一个整数,并从中读取整数。但是无论何时我运行代码,文件都不会打开。这是我的代码:

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();

1 个答案:

答案 0 :(得分:0)

如果文件不存在,那么您必须再次尝试打开它而不使用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 file\n";
    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";