Discussion:
Doubt about std::ifstream's getline() and seekg()
(too old to reply)
Assertor
2006-02-26 06:25:35 UTC
Permalink
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'.
Heinz Ozwirk
2006-02-26 07:37:24 UTC
Permalink
Post by Assertor
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
Assertor
2006-02-26 08:33:31 UTC
Permalink
:-) Thanks Sir.

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

Loading...