How to go through a file multiple times?

I am going through a file once in one do-while loop, closing the ifstream and re-opening it, and then running through 3 other do-while loops. The files open and close sucessfully, but only the body of the top loop in the code executes. Shouldn't the input go back to the beginning if I close and reopen the file?

This is how I'm closing and reopening:
infile.close();
infile.open(ifname, ios::in);

I COULD make infile, infile2, infile3, infile4.. but do I really need to do that if I'm just opening the same file?
Last edited on
Just change the position of the "get" pointer back to the start of the file.

http://www.cplusplus.com/reference/iostream/istream/seekg/
1
2
3
4
5
6
std::ifstream ifs;

// ... stuff ...

ifs.seekg(0); // move to beginning
ifs.clear(); // clear flags (like EOF) 
I typically just let the scope destroy and recreate the stream:
1
2
3
4
5
for( int i = 0; i < n; ++i )
{
    std::ifstream fin( filename );
    // process file
}
Topic archived. No new replies allowed.