尝试读取二进制文件会清除文件本身

Trying to read binary file clears the file itself

本文关键字:文件 清除 读取 二进制文件      更新时间:2023-10-16

我刚刚开始使用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 的文件。

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

打开时丢弃流的内容

所以只需使用:

// 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;
}

不是读取文件的适当方法。想想空文件会发生什么:打开它后,它是"好的"(请记住,eofbit 仅在某些输入操作遇到 eof 时才设置(。然后get失败,保持原样ch,从而调用未定义的行为。在输入操作后直接更好地测试流状态:

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

有关读取文件的更多背景信息,请参阅为什么循环条件中的 iostream::eof 被认为是错误的?