Problem with eof().

When I tried to read and extract each line from a .txt file,then copy these data to a buffer array,the get pointer reached the end of file and the eof() bit is set and the problem is no more read attemp from that file allowed.Please tell me how can I access the file again?I tried to clear the eof() bit but it didn't work.
And one more question: how can I delete some character from that .txt file without destroy its content?
Thanks in advance.
seekg() will reposition your pointer so that after the eof bit is cleared, it's not automatically re-set because of your pointer being at the end of your file.
http://cplusplus.com/reference/iostream/istream/seekg/

As for your second question... I'm not sure if there is a way using solely ofstream to do that.

Welcome to the forum.

-Albatross
Last edited on
Don't loop on EOF.
Loop on good().

1
2
3
4
while (getline( f, s ).good())
  {
  ...
  }

You can shorten that to

1
2
3
4
while (getline( f, s ))
  {
  ...
  }

Hope this helps.
And one more question: how can I delete some character from that .txt file without destroy its content?


Don't understand the question. You can't really delete anything from a file but you can rewrite to the file or append to the file or write to a new file. What are you trying to do?
Hi Duoas, almost all books say loop on EOF. why it is an error/prune?
If you loop on eof() you won't be checking for fail() or bad(). Testing for good() or simply testing the stream as Duoas showed will fail in any of these cases.
Heh heh heh...

almost all bad books say loop on EOF.
Because the people who wrote said books have never done any useful file I/O in C or C++ themselves... or they are just incompetent.

why is it an error
Because it may compute infinitely when fat electrons get into your computer.
@tranlong1612

To start reading the file again you can use:

1
2
3
4
std::ifstream ifs("my-file.txt");

ifs.clear(); // clear all error flags
ifs.seekg(0); // goto beginning of file. 


If you want to delete a character from a text file then I suppose you will need to copy every character after the one you wish to delete back one. However, what are you trying to do? That sounds rather inefficient for most purposes.
Last edited on
Topic archived. No new replies allowed.