【问题标题】:Opening binary file打开二进制文件
【发布时间】: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 &lt;fstream&gt;(请参阅在线参考中的示例)。
  • 您似乎在使用score_file.is_open() 来检查文件是否已经存在。但如果是false,并不代表该文件不存在。这意味着您无法打开它,也无法对其进行写入/读取。一个原因可能是您没有读取/写入文件的权限。据我所知fstream 会在文件不存在时创建该文件。

标签: c++ file binary


【解决方案1】:

如果文件不存在,那么您必须在没有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";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 2012-02-17
    相关资源
    最近更新 更多