So I have a function to detrermine the number of lines in my program. It does this by taking an ifstream& object as a parameter, and using getline( ifile, dummystr ) until EOF is hit, at which point the loop breaks and I try to use ifile.seekg( 0, ios::beg ) so I can read the file from outside the function using the same reference.
For some reason, when this function returns and I try to read the contents of the same file, it seems to be hitting EOF right away and doesn't read anything.
Here is the relevant code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//get number of lines from file pointedto by ifile
int getLines( ifstream& ifile )
{
int size = 0;
string dummy;
if ( ifile.is_open() )
{
while ( getline( ifile, dummy ) )
{
size++;
}
ifile.seekg ( 0, ios::beg );
return size;
}
else
cout << "Could not read file for line counting...\n";
return 0;
}
and to read it:
1 2 3 4 5 6 7 8 9 10 11 12
while ( !ifile.eof() )
{
getline( ifile, line );
if ( i % 5000 == 0 )
{
cout << i << " of " << numLines << " entries processed...\n";
}
StringWrapper wrapper = StringWrapper( line );
tree->add( wrapper );
i++;
}
the loop in the second snippet is never done. I suspect that the seekg(0, ios::beg) is not doing as I thought...
Thanks for any help on this. I have searched for alternative ways to do this, and short of opening the same file twice, this is the only way I have found.
The C++ get and put pointers are supposed to be orthogonal, but they are not. Most existing software uses the same pointer for both get and put operations, and so the STL, consequently, does also.
Never assume that the get pointer is unmodified after a put operation, and never assume that the put pointer is unmodified after a get operation.