尝试读取二进制文件会清除文件本身
Trying to read binary file clears the file itself
我刚刚开始使用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 被认为是错误的?
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- ifstream文件在从行中读取时被清除
- 如何清除/清空已打开的文件C++
- 如何在Qt Designer UI文件中清除QMainWindow的几何标记
- 尝试读取二进制文件会清除文件本身
- 如何使用文件*清除文件
- 清除C 中所有文件中的数据
- 如何在C++的追加模式下清除文件
- 当我写入我的文件时,它会清除该文件中以前的所有数据
- 删除IE中"缓存清除"上的文件
- 有没有办法在C ++中动态清除文本文件的内容
- 我正在尝试清除数据文件中具有某些条件的特殊字符,但这些条件不满足
- 如何在使用fstream打开文件后清除文件的内容
- 如何正确清除文件在linux中
- 在启动时清除文件的内容,然后追加
- 修改.ui文件需要“清除”
- c++清除特定位置后的文件内容
- 为什么关闭文件不会自动清除错误状态?
- 如何创建未清除的文件