0

I'm reading a file through a function like this:

#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 file has 3 lines:

first
second
third

I expected the output:

3
first

Instead I get:

3
(nothing)

why is my seekg not working?

Zasito
  • 281
  • 1
  • 7
  • 17

2 Answers2

3

Because seekg() fails if the stream has reached the end of the file (eofbit is set), which occurs due to your getline looping. As sftrabbit implies, calling clear() will reset that bit and should allow you to seek properly. (Or you could just use C++11, in which seekg will clear eofbit itself.)

JAB
  • 20,783
  • 6
  • 71
  • 80
0

Use iterators for read from the file

std::fstream file( "myfile.txt", std::ios::out );
std::string data = std::string(
     std::istreambuf_iterator<char>( file ),
     std::istreambuf_iterator<char>() );
  • Iterators are nice, but the question was regarding why the method provided does not work, not if there is a better method (and all you're doing is shifting the work from file routines to operations on a string, which could also be done via iterators but says nothing about the original problem). – JAB Jan 14 '14 at 20:04