2013-09-23 19 views
0

赫雷什我的代碼二進制文件不能多次使用?

#include <iostream> 
#include <fstream> 

using namespace std; 

struct a 
{ 
    int x; 
    int b; 
}; 

int main() 
{ 

ifstream rfile("test.bin", ios::binary); 
a ob; 

//Reading from the file for the first time works fine. 
rfile.read((char*)&ob, sizeof(ob)); 
while (rfile) 
{ 
    cout<<ob.x<<endl; 
    rfile.read((char*)&ob, sizeof(ob)); 
} 
rfile.seekg(0, ios::beg); 

cout<<"G:"<<rfile.tellg()<<endl; //Outputs -1 
rfile.read((char*)&ob, sizeof(ob)); 
while (rfile) 
{ 
    cout<<ob.x<<endl; 
    rfile.read((char*)&ob, sizeof(ob)); 
} 


return 0; 
} 

輸出是

3 
1 
G:-1 

如在第一環路作品和第二環路dosent工作,因爲指針的位置是在-1即使使用seekg()之後。這是爲什麼發生?

回答

3

如果ifstream在第一次while循環後處於無效狀態,則需要在流的任何其他操作之前重置流狀態標誌。

rfile.read((char*)&ob, sizeof(ob)); 
} 
rfile.clear(); 
rfile.seekg(0, ios::beg); 

,而不是

rfile.read((char*)&ob, sizeof(ob)); 
} 
rfile.seekg(0, ios::beg); 
1

這是因爲在C++ 98中,seekg()與C++ 11的行爲不同。在C++ 98中,如果在調用之前設置了eofbit標誌,則該函數失敗(設置失敗位並返回)。你可以檢查返回值來驗證。

在C++ 11中,如果在調用之前設置該函數,該函數會清除eofbit