Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting the End of file state of a ifstream object in C++

Tags:

I was wondering if there was a way to reset the eof state in C++?

like image 220
Steffan Harris Avatar asked Oct 06 '11 23:10

Steffan Harris


People also ask

How do I go back to the beginning of a file in C++?

The rewind() function in C++ sets the file position indicator to the beginning of the given file stream.

Does ifstream automatically close the file?

Note that any open file is automatically closed when the ifstream object is destroyed.

Do you need to close ifstream C++?

No, this is done automatically by the ifstream destructor.


1 Answers

For a file, you can just seek to any position. For example, to rewind to the beginning:

std::ifstream infile("hello.txt");  while (infile.read(...)) { /*...*/ } // etc etc  infile.clear();                 // clear fail and eof bits infile.seekg(0, std::ios::beg); // back to the start! 

If you already read past the end, you have to reset the error flags with clear() as @Jerry Coffin suggests.

like image 143
Kerrek SB Avatar answered Sep 23 '22 01:09

Kerrek SB