2012-02-27 30 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