bq54
bq54

Reputation: 667

Returning to beginning of file after getline

So i've read all the lines from a file thusly

while (getline(ifile,line))
    {
        // logic
    }

Where ifile is an ifstream and line is a string

My problem is I now want to use getline over again, and seem to be unable to return to the beginning of the file, as running

cout << getline(ifile,line);

Will return 0

I've attempted to use:

ifile.seekg (0, ios::beg);

To no avail, it seems to have no effect. How do I go back to the start of the file?

Upvotes: 60

Views: 130845

Answers (3)

Konrad Rudolph
Konrad Rudolph

Reputation: 546173

Since you have reached (and attempted to read past) the end of the file, the eof and fail flags will be set. You need to clear them using ifile.clearthen try seeking:

ifile.clear();
ifile.seekg(0);

Upvotes: 108

iko79
iko79

Reputation: 1268

FYI: In my case, the order DID matter, thus

  1. clear
  2. seek

otherwise the next getline operation failed (MSVC v120)

Upvotes: 2

Angus Comber
Angus Comber

Reputation: 9708

This is because the eof flag has been set on the stream - due to you reaching the end of the file. so you have to clear this as an additional step.

Eg

ifile.clear();
ifile.seekg (0, ios::beg);

Upvotes: 12

Related Questions