Can't get fstream to seekg back to 0 after EOF flag set

598 views Asked by At

So I've got this fstream that I'm reading from my file with, and I get this insane bug when trying to read from my file after the EOF flag is set (or at least that's what I think is happening).

This is the scope of my problem:

if (!reader.good())
        {
            reader.clear();
            reader.seekg(0, ios::beg);
        }
int test = reader.tellg();
reader.seekg((index / 10) * 10 * sizeof(TrieNode));
test = reader.tellg();
reader.read((char*)TrieBuff, 10 * sizeof(TrieNode));
test = reader.tellg();

I've added the integer 'test' so that I could track the position of the stream in the debugger for every step of the way. Now what I've been seeing in the debugger is that even when the program enters the 'if' and clears the fstream, test still equals -1 afterwards! And then nothing is read into TrieBuff. I have no idea what to do here.

Here's the entire function just incase it's relevant:

// Takes an fstream opened at the doc's trie file. Returns the node at the 
    // index specified, using the TrieBuff. (The index is the node's serial number.)
    TrieNode get_node_at_index(fstream& reader, int index)
    {
        if (TrieBuff[0].data.nodeserialnr == -1 ||
            index > TrieBuff[9].data.nodeserialnr || index < TrieBuff[0].data.nodeserialnr)
        {
            if (!reader.good())
            {
                reader.clear();
                reader.seekg(0, ios::beg);
            }
            int test = reader.tellg();
            reader.seekg((index / 10) * 10 * sizeof(TrieNode));
            test = reader.tellg();
            reader.read((char*)TrieBuff, 10 * sizeof(TrieNode));
            test = reader.tellg();
            int x = 0;
        }
        return TrieBuff[index % 10];
    }
2

There are 2 answers

0
Scott Steinbach On BEST ANSWER

So the answer was, as some suggested, that the fstream was not opening correctly. I hadn't realized that stream.good() will return true even if the stream is not opened. Thanks everyone for contributing.

3
kravi On

I couldn't understand the use of (index / 10) * 10 * sizeof(TrieNode). It it is used purposefully, then please check that it will be evaluated to 0 for the index, which is not divisible by 10. Since index / 10 is an integer division. I guess due to that read pointer is not moving forward.