2012-02-27 79 views
1

我正在使用Ubuntu 10.04和gcc。我有我自己的幻数的二进制文件。当我读取文件时,幻数不一样。溪流接缝是正确的。std :: fstream似乎以不同的大小读取

书写神奇的数字:

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是下一个输入的合法值。那么,为什么他们不同,我如何解决这个问题?

+0

在STL中没有'fstream',加上我非常怀疑你正在使用它。 – Fanael 2012-02-27 17:50:23

+0

@Fanael我写过STL的fstream吗?在标题中它说std :: fstream。如果是这样,是否有人可以更改标题? – JoshuaBehrens 2012-03-30 00:05:32

+0

是的,你做到了。请参阅[修订历史记录](http://stackoverflow.com/posts/9469361/revisions)。 – Fanael 2012-04-04 11:44:15

回答

3

在第二种情况下,operator>>正在跳过字符值12. operator>>12识别为空格,并跳过它,搜索下一个有效字符。

尝试使用未格式化的输入操作(如chfile.read()chfile.get())。

+0

感谢您的帮助。修复了这个问题。 – JoshuaBehrens 2012-02-28 10:31:54

+0

@JoshuaBehrens,我很高兴你在StackOverflow上的体验是积极的。请*上​​传*每个有用的答案(点击向上的三角形),*接受*最好的答案(点击复选标记)。然后阅读其他人的问题并回答他们,如果可以的话。 – 2012-02-28 14:26:47

+0

我刚刚注册,但自3(?)年起使用了stackoverflow。但是,谢谢你的帮助。 – JoshuaBehrens 2012-03-30 00:07:05

1

您不应该使用<<>>与二进制文件,它们用于格式化读取和写入。
尤其是,它们会对0xC(即换页)等空白字符进行特殊处理,这使得它们不适用于二进制I/O。

+0

感谢您的帮助。修复了这个问题。 – JoshuaBehrens 2012-02-28 10:30:09