Rouki
Rouki

Reputation: 2355

fstream and file pointer moving

Ive been trying saving the file pointer location before resetting it and then set it back but things don't seem to work as I want.

I came up with:

fstream f;

// open...

long long p = f.seekg(); // Save previous location

f.seekg(std::ios::beg);  // Set ptr to the file beginning

// Work with the file...

f.seekg(p);              // return ptr to the previous location (p)

If I try to print the fileptr location after the following commands the value is -1.. Is it because I reached EOF when I worked with the file? And if I cant set it back to the previous location with seekg, what other alternatives I should consider?

thanks

Upvotes: 1

Views: 4498

Answers (3)

Matteo Italia
Matteo Italia

Reputation: 126877

long long p = f.seekg();

Cannot even compile, you probably mean tellg.

f.seekg(std::ios::beg);

this is wrong; seekg has two overloads, one that accepts a position in the stream, and one that accepts an offset from some particular position, specified with an enum. The std::ios::beg/cur/end only work with this other overload. So, here you want

f.seekg(0, std::ios::beg);

And, most importantly, if your stream is in a dirty state (eof, fail, bad) the seek won't have any effect. You have to clear the status bit first, using f.clear().

By the way, if you want to go safe storing the file pointer location, you should use the type std::istream::streampos. So, summing it up:

std::istream::streampos p = f.tellg(); // or, in C++11: auto p = f.tellg();
// f.clear() here if there's a possibility that the stream is in a bad state
f.seekg(0, std::ios::beg);
// ...
f.clear();
f.seekg(p);

Upvotes: 5

P0W
P0W

Reputation: 47824

Reset the flags first, if you encounter the EOF

f.clear();                 // clear fail and eof bits
f.seekg(p, std::ios::beg); 

Upvotes: 0

David G
David G

Reputation: 96845

tellg returns the file position indicator:

std::istream::pos_type p = f.tellg();
//                           ^^^^^

Upvotes: 0

Related Questions