在C++中使用 seekg 时出现问题

Problems using seekg in C++

本文关键字:问题 seekg C++      更新时间:2023-10-16

我正在通过这样的函数读取文件:

#include <iostream>
#include <fstream>
#include <string>
...
void readfile(string name){
    string line;
    int p = 0;
    ifstream f(name.c_str());
    while(getline(f,line)){
        p++;
    }
    f.seekg(0);
    cout << p << endl;        
    getline(f,line);
    cout << line << endl;
}

小米文件有3行:

first
second
third

我期望输出:

3
first

相反,我得到:

3
(nothing)

为什么我的搜索不起作用?

因为如果流已到达文件末尾(eofbit已设置),则seekg()失败,这是由于您的getline循环而发生的。正如 sftrabbit 所暗示的那样,调用clear()将重置该位,并且应该允许您正确搜索。(或者你可以只使用 C++11,其中seekg将清除eofbit本身。

使用迭代器从文件中读取

std::fstream file( "myfile.txt", std::ios::out );
std::string data = std::string(
     std::istreambuf_iterator<char>( file ),
     std::istreambuf_iterator<char>() );