0

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

#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;
}

Mi 文件有 3 行:

first
second
third

我期望输出:

3
first

相反,我得到:

3
(nothing)

为什么我的 seekg 不起作用?

4

2 回答 2

2

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

于 2014-01-14T18:59:31.220 回答
0

使用迭代器从文件中读取

std::fstream file( "myfile.txt", std::ios::out );
std::string data = std::string(
     std::istreambuf_iterator<char>( file ),
     std::istreambuf_iterator<char>() );
于 2014-01-14T19:16:09.647 回答