簡體   English   中英

c ++ eof和failbit在讀取二進制文件的中間

[英]c++ eof and failbit in the middle of reading binary file

我在讀取二進制文件時遇到了麻煩。 它似乎沒有讀到最后:

// get file size
ifs.open (inFile.c_str(), ios::binary | ios::ate);
cout << "file size:  " << ifs.tellg() << endl;;
ifs.close();

// read file
ifs.open (inFile.c_str(), ios::in | ios::binary);
int counter = 0;
char c = 0;
for (counter = 0; ifs; ++counter)
    ifs >> c;

cout << "last char:  " << int(c) << endl;
cout << "read bytes: " << counter << endl;
cout << "fail? " << (ifs.fail() ? "yes" : "no") << endl;
cout << "bad?  " << (ifs.bad() ? "yes" : "no") << endl;
cout << "eof?  " << (ifs.eof() ? "yes" : "no") << endl;
ifs.close();

下面是輸出。 我不明白為什么我在文件中間得到那個eofbit以及為什么它與failbit一起出現:

file size:  289384
last char:  1
read bytes: 288598
fail? yes
bad?  no
eof?  yes

我在 Unix 系統上得到它

我做了一個測試,發現了問題。 一旦將ofs << c添加到 for 循環中, ofs << c明顯了。

它不是讀取空白。

您可以通過添加#include <iomanip>ifs >> noskipws或使用二進制輸入函數(如ifs.get(c)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM