在C ++中使用seekg的问题

时间:2014-01-14 18:54:31

标签: c++ file stream seekg

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

#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)

为什么我的寻求不起作用?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

使用迭代器从文件中读取

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