By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,007 Members | 1,023 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,007 IT Pros & Developers. It's quick & easy.

Doubt about std::ifstream's getline() and seekg()

P: n/a
Hi, All.

(VC++6.0)
I found some strange thins when using getline() and seekg() of
std::ifstream.

After the file position of an open file was shift to the end of the
file,
seekg() did not work rightly. (i.e. I could not move the file position
to the begin or some position using seekg())

see the following example code.

std::ifstream fStream("a.dat", std::ios::in);

fStream.seekg(3, std::ios::beg);
pos = fStream.tellg(); //<--- I checked if the postion is rigglty
moved and checked again by
getLine().

while( !fStream.eof() )
{
fStream.getline(bufff, MAX_LINE);
.....
}

fStream.seekg(3, std::ios::beg);
pos = fStream.tellg(); //<--- the position is move to the 3 from
the begin.
//in fact, the fstream's
postion pointed at the end of the file.

if( fStream.eof() )
std::cout<<"the end of this file\n"; <---- the string was printed.
:-(.
??
So. When the file position is shifted to the end of a file by using
getline(),
I CAN NOT move the file position????
(In this case, To go to the fist position of the file, I closed
the opened file then I reopened the file).
And for ur imformation,
In case of std::ofstream, seekp() was simlar to the above seekg() of
std::ifstream.
After the position was moved to end by getline(), though I move the
position by using seekp(), tellp() returned '-1'.

Feb 26 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
"Assertor" <gi******@gmail.com> schrieb im Newsbeitrag
news:11**********************@j33g2000cwa.googlegr oups.com...
Hi, All.

(VC++6.0)
I found some strange thins when using getline() and seekg() of
std::ifstream.

After the file position of an open file was shift to the end of the
file,
seekg() did not work rightly. (i.e. I could not move the file position
to the begin or some position using seekg())

see the following example code.

std::ifstream fStream("a.dat", std::ios::in);

fStream.seekg(3, std::ios::beg);
pos = fStream.tellg(); //<--- I checked if the postion is rigglty
moved and checked again by
getLine().

while( !fStream.eof() )
{
fStream.getline(bufff, MAX_LINE);
.....
}


Once a stream has been put into a bad state it remains in that state until
it is cleared. So when you have detected the end of a file or some error,
clear that exceptional state. In your code, add fStream.clear() after the
loop above.

HTH
Heinz
Feb 26 '06 #2

P: n/a
:-) Thanks Sir.

I resolved my problem by adding fStream.clear() according to what u
adviced.

Feb 26 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.