Infinite Loop when using ifstream::seekg()

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

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
Thanks! It works!
Topic archived. No new replies allowed.