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

A

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);
.....
}

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::eek:fstream, 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'.
 
H

Heinz Ozwirk

Assertor said:
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
 
A

Assertor

:) Thanks Sir.

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top