In the previous response, how will line 14 ever get executed? I think it would execute in the case when the length is neither zero, nor is it non-zero.
seekg() is telling the computer to move the pointer a certain number of bytes along. The values ios::beg, ios::cur and ios::end are just values which the machine understands to mean, "from the beginning" etc.
eof is a different type of animal. It's a condition which occurs when you attempt to read some data, but there is nothing more to read. It isn't related to position as such, but simply to the success or otherwise of a read operation.
The problem with your logic (from the compiler's point of view) is that the final
if
does not have an
else
, so it considers there may be some condition where the
if
is not true. After all, if that were not the case, why would you bother using an
if
at all?
And the fact that you restored the file position in that scenario shows you agree with the compiler. :)
As for resetting the file position, a well-behaved function would first of all store the
current position, and then restore that position when you are finished.
One more thing, since all you ever return is a yes/no result, this seems a good candidate for a boolean return type, not an integer.
1 2 3 4 5 6 7 8 9 10
|
bool BadFile(ifstream &fin)
{
unsigned int pos = fin.tellg(); // save current position
fin.seekg(0, ios::end); // Set position zero bytes from the end
unsigned int filelength = fin.tellg(); // get the length
fin.seekg(pos, ios::beg); // restore saved position
return (filelength == 0); // return true if file is empty
}
|