簡體   English   中英

ifstream seekg有什么問題

[英]What's wrong with the ifstream seekg

我正在嘗試尋找並重新讀取數據。 但代碼失敗了。

代碼是

std::ifstream ifs (filename.c_str(), std::ifstream::in | std::ifstream::binary);

std::streampos pos = ifs.tellg();

std::cout <<" Current pos:  " << pos << std::endl;

// read the string
std::string str;
ifs >> str;

std::cout << "str: " << str << std::endl;
std::cout <<" Current pos:  " <<ifs.tellg() << std::endl;

// seek to the old position
ifs.seekg(pos);

std::cout <<" Current pos:  " <<ifs.tellg() << std::endl;

// re-read the string
std::string str2;
ifs >> str2;

std::cout << "str2: (" << str2.size() << ") " <<  str2 << std::endl;
std::cout <<" Current pos:  " <<ifs.tellg() << std::endl;

我的輸入測試文件是

qwe

輸出是

 Current pos:  0
str: qwe
 Current pos:  3
 Current pos:  0
str2: (0)
 Current pos:  -1

誰能告訴我什么是錯的?

ifs >> str; 因為到達文件的末尾而結束,它設置了eofbit。

在C ++ 11之前, seekg()無法從流的末尾尋找(注意:你的實際上是這樣做的,因為輸出是Current pos: 0 ,但這並不完全符合:它應該無法尋找或應該清除eofbit and seek)。

無論哪種方式,為了解決這個問題,你可以執行ifs.clear(); ifs.seekg(pos);之前ifs.seekg(pos);

看起來它正在讀取它正在擊中EOF並在流狀態中標記它。 執行seekg()調用時,流狀態不會改變,因此下一次讀取檢測到EOF位已設置並返回而不讀取。

暫無
暫無

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

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