2013-05-03 101 views
13

我正在尝试查找并重新读取数据。但代码失败。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 

谁能告诉我有什么不对?

+0

可能重复[seekg()函数将失败(http://stackoverflow.com/questions/11264764/seekg-function-fails) – amo 2014-09-16 23:00:33

回答

5

它看起来像在读取它正在击中EOF的字符并将其标记为流状态。在执行seekg()调用时,流状态不会更改,因此下一次读取会检测到EOF位已设置并在未读取的情况下返回。

+5

解决的办法是调用'ifs.clear()'。 – 2013-05-03 17:23:12

27

ifs >> str;因达到文件结束而结束时,它设置eofbit。

直到C++ 11,seekg()无法从流结束(注意:你实际上是这样做的,因为输出是Current pos: 0,但这并不完全符合:它应该无法搜索或应该清除eofbit和寻求)。

无论哪种方式,要解决的是,你可以执行ifs.clear();ifs.seekg(pos);