【问题标题】:Trying to read binary file clears the file itself尝试读取二进制文件会清除文件本身
【发布时间】:2017-10-08 18:34:24
【问题描述】:

我刚开始在 C++ 中处理二进制文件,并且我已经成功地编写和读取了一个 (.bin) 文件。代码如下:

#include <iostream>
#include <cstring>
#include <fstream>

using namespace std;

int main()
{
    char input[100];

    strcpy(input, "This is a string");

    fstream file("example.bin", ios::binary | ios::in | ios::out | 
ios::trunc);

if(!file.is_open())
{
    cerr << "Error opening file.\n";
} else {
    for(int i = 0; i<= strlen(input); i++)
    {
        file.put(input[i]);
    }
}

file.seekg(0);
char ch;

while(file.good())
{
    file.get(ch);
    cout<<ch;
}
}

这奏效了。之后,我尝试重新设计代码以读取二进制文件。主要更改是:将 fstream 更改为 ifstream(读取),删除了写入文件的部分。代码准备好后,我找到了一个我想读取的文件 (eof0.bin)。当我使用代码时,我唯一得到的是一个空字符串。我注意到文件的初始大小是 37 KB,而使用我的程序后它变成了 0。我想知道,我的程序是如何清除二进制文件中的数据的?

这是我用来读取文件的代码。

#include <iostream>
#include <cstring>
#include <fstream>

using namespace std;

int main()
{

ifstream file("eof0.bin", ios::binary | ios::in | ios::out | ios::trunc);

if(!file.is_open())
{
    cerr << "Error opening file.\n";
} else {
    // Nothing.
}

file.seekg(0);
char ch;

while(file.good())
{
    file.get(ch);
    cout<<ch;
}


}

一切都可以编译,但在 37 KB 大小的文件上使用它会给我一个 0 KB 的文件。

【问题讨论】:

  • 为什么不显示有效的代码,而不显示无效的代码?
  • 在问题中提供导致意外行为的代码以及一个小的示例输入文件(其内容为文本形式)会更好......
  • 代码实际编译,所以成功了。
  • 只需要阅读为什么要打开输出?
  • 另外,ios::trunc 表示它将截断(清空)文件

标签: c++ file binary fstream ifstream


【解决方案1】:

您使用打开模式 std::ios_base::trunc 打开。从http://en.cppreference.com/w/cpp/io/ios_base/openmode可以看出

打开时丢弃[s]流的内容

所以只需使用:

// also dropped ios::out since you only want to read, not write
ifstream file("eof0.bin", ios::binary | ios::in);

还有,这个

char ch;
while(file.good())
{
    file.get(ch);
    cout<<ch;
}

不是读取文件的合适方式。想想一个空文件会发生什么:打开它后,它是“好”的(记住,只有在某些输入操作遇到 eof 时才会设置 eofbit)。然后get 失败,留下ch 原样,从而调用未定义的行为。在输入操作之后直接对流状态进行更好的测试:

char ch;
while (file.get(ch)) {
  // use ch
}
// optionally distinguish eof and fail cases

有关读取文件的更多背景信息,请参阅Why is iostream::eof inside a loop condition considered wrong?

【讨论】:

  • 天哪,它奏效了。它输出的不是我所期望的,但至少我已经阅读了文件。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多