std::fstream似乎有不同的大小
std::fstream seems to read in different sizes
我正在开发ubuntu 1004和一个gcc。我有一个二进制文件,里面有我自己的幻数。当我读取文件时,幻数是不一样的。溪流接缝正确。
书写神奇数字:
std::fstream chfile;
chfile.open(filename.c_str(), std::fstream::binary | std::fstream::out);
if (chfile.good())
{
chfile << (unsigned char)0x02 << (unsigned char)0x46 << (unsigned char)0x8A << (unsigned char)0xCE;
// other input
chfile.close();
}
阅读魔术数字:
std::fstream chfile;
chfile.open(filename.c_str(), std::fstream::binary | std::fstream::in);
if (chfile.good())
{
unsigned char a,b,c,d;
chfile >> a;
chfile >> b;
chfile >> c;
chfile >> d;
printlnn("header must : " << (int)0x02 << ' ' << (int)0x46 << ' ' << (int)0x8A << ' ' << (int)0xCE); // macro for debugging output
printlnn("header read : " << (int)a << ' ' << (int)b << ' ' << (int)c << ' ' << (int)d);
chfile.close();
}
当我使用02 46 8A CE作为幻数时,它是可以的(正如输出所说):
header must : 2 70 138 206
header read : 2 70 138 206
但当我使用EA 50 0C C5时,输出为:
header must : 234 80 12 197
header read : 234 80 197 1
最后一个1是下一个输入的合法值。那么,为什么它们不同,我该如何解决呢?
在第二种情况下,operator>>
跳过字符值12。operator>>
将12
识别为空白,并跳过它,搜索下一个有效字符。
请尝试使用未格式化的输入操作(如chfile.read()
或chfile.get()
)。
您不应该将<<
和>>
与二进制文件一起使用,它们用于格式化读取和写入
特别是,它们对空白进行特殊处理,如0xC(即formfeed),这使它们不适合二进制i/O。
相关文章:
- 使 std::fstream 写入文件末尾,但从头开始读取
- 为什么当我在 std::string 中打开文件名的 fstream 时出现"no matching function"错误?
- 自定义 std::fstream,std::filebuf 的溢出和下溢函数未为每个字符调用
- Windows std::fstream 修改文件后打开()?
- std::fstream 在 MSVC 和 G++ 上使用 UTF-8 的不同行为
- std::getline with std::fstream
- 变量 std::fstream 文件具有初始值设定项,但类型不完整 编译错误
- std::fstream 已使用,但编译器抛出错误
- std::fstream 需要很长时间才能将大数据写入.csv文件中
- STD :: FSTREAM在使用预先分配的内存时在Main之后崩溃
- STD :: FSTREAM文件处理重复使用的问题
- 即使在包含 std 命名空间之后,fstream 在 Visual Studio 2017 中也无法正常工作
- 使用“QUrl”作为文件路径馈送到“std::fstream”
- 为什么与cstdio和std::fstream相比,SDL_RWops在写入文件时表现如此糟糕
- 检查是否使用std :: fstream编写文件
- 为什么 std::fstream 返回 void 而不是 bool
- 为什么'ifstream'和'ofstream'被添加到"std",而'fstream'可以同时达到这两个目的?
- 正在从std::fstream检索文件描述符
- 将对象序列化为加密的 std::fstream (C++)
- 当"std::fstream"无法打开时会引发异常吗?