Infinite Loop when using ifstream::seekg()

Mar 14, 2015 at 5:35pm
I'm writing a program where ifstream reads some characters from file, and skips some. However, when EOF is reached, it still tries to read, creating an infinite loop.
I have this type of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
ifstream inp("data.txt");

while(!inp.eof())
{
    char buf[4];

    inp.read(buf,4);

    if(buf==something)
    {
        //Do something
    }
    else
    {
        //skip 32 characters
        inp.seekg(32, ifstream::cur);
    }
}


This code creates an infinite loop! Why seekg() doesn't stop when end of file is reaced? How to make this code work?
Last edited on Mar 14, 2015 at 5:35pm
Mar 14, 2015 at 6:10pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ifstream inp("data.txt");

char buf[4];

while(inp.read(buf,4))
{
    if(buf==something)
    {
        //Do something
    } else {
        //skip 32 characters
        inp.seekg(32, ios_base::cur);
    }
}

Mar 14, 2015 at 7:38pm
Using .eof() as a loop condition is almost always wrong. If read or seekg fails for some reason the failbit and/or badbit state will be set. It will cause all future read operations to fail so the end of the file is never reached and eofbit is never set, which is probably why your loop never stop.

http://en.cppreference.com/w/cpp/io/ios_base/iostate
Mar 15, 2015 at 10:13am
Thanks! It works!
Topic archived. No new replies allowed.