ved*_*eda 17 c++ 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;
Run Code Online (Sandbox Code Playgroud)
我的输入测试文件是
qwe
Run Code Online (Sandbox Code Playgroud)
输出是
Current pos: 0
str: qwe
Current pos: 3
Current pos: 0
str2: (0)
Current pos: -1
Run Code Online (Sandbox Code Playgroud)
谁能告诉我什么是错的?
Cub*_*bbi 32
当ifs >> str;因为到达文件末尾而结束时,它会设置eofbit.
在C++ 11之前,seekg()无法寻求远离流的末尾(注意:你的实际上是这样,因为输出是Current pos: 0,但这并不完全符合:它应该无法寻找或者应该清除eofbit并寻求).
无论哪种方式,要解决的是,你可以执行ifs.clear();前ifs.seekg(pos);