- 論壇徽章:
- 0
|
ls:
通過使用你給的那段代碼,我發(fā)現(xiàn),是可以正常的讀取到文件結尾的,那么看來eof這個函數(shù)是沒有問題.
我把in.read修改為in.getline結果程序沒有讀到文件結尾就跳出了,所以我覺得是in.getline()在使用時候的問題.經(jīng)過排查,我發(fā)現(xiàn)當遇到文件中的一個字符的時候,in的流狀態(tài)變?yōu)閒ail(),于是導致了沒有讀到最后.
有誰能解釋一下什么時候會在讀文件的時候出現(xiàn)流狀態(tài)是fail(),這種情況很常見!
- #include <iostream>
- #include <fstream>
- using namespace std;
- #define BUFSIZE 20
- int main()
- {
- ifstream in("e:\\a.txt");
- cout << in.gcount() << endl;
- char buf[BUFSIZE];
- int i = 0;
- do {
- //in.read(buf, BUFSIZE );
- in.getline(buf, 20); //改動的地方
- std::streamsize n = in.gcount();
- cout.write( buf, n );
- } while( in.good() );//
- if( in.bad() || !in.eof() )
- {
- cerr << "error" << endl;
- }
- in.close();
- }
復制代碼 |
|