|
|
| fstream behavior |
|
Steve Terry
Member #1,989
March 2002
|
I can't understand why fstream sets the failbits when the file you try to open does not exist. I ran into a strange problem today related to fstream in that if the failbit is set it's easy to run into an infinite loop:
The problem is that the first fin.open failed which set the failbit while the second fin.open succeeded but did not reset the failbits. When you call getline it will never be able to read and therefore never hit the eof. Simple fix is to add fin.clear() before getline but it's not evident by the logic above that you must do that. Shouldn't fstream reset the failbits if open succeeds? ___________________________________ |
|
Edgar Reynaldo
Major Reynaldo
May 2007
|
I use a different check to see if the fstream is valid. Instead of using fstream.is_open() , I use either a boolean test with operator ! or a call to the fstream.good() function.
It makes sense that if you open a new fstream that the failbit shouldn't be set since it hasn't actually failed , I think you're right about that. - Append - bool file_error_flag = false; fstream file; file.open(".\\nonexistentfile.txt"); if (file.good()) { cout << "File stream incorrectly reported as good when opening a non existent file" << endl; } else { file_error_flag = true; } file.open(".\\realfile.txt"); if (file_error_flag) { if (!file.good()) { cout << "File stream incorrectly reported as not good() when opening an actual file" << endl; } }
My Website! | EAGLE GUI Library Demos | My Deviant Art Gallery | Spiraloid Preview | A4 FontMaker | Skyline! (Missile Defense) Eagle and Allegro 5 binaries | Older Allegro 4 and 5 binaries | Allegro 5 compile guide |
|
Arthur Kalliokoski
Second in Command
February 2005
|
Quote: Simple fix is to add fin.clear() before getline but it's not evident by the logic above that you must do that. Shouldn't fstream reset the failbits if open succeeds? It might be considered a "sticky bit" that you must explicitly clear. Then you could detect errors indefinitely later, like glError() or fxam do. [EDIT] glError() clears them as you fetch the errors. They all watch too much MSNBC... they get ideas. |
|
Karadoc ~~
Member #2,749
September 2002
|
Edgar Reynaldo said: Actually , though , I understand why the failbit is set when opening a file doesn't work. You wouldn't want ios::good() to return true when a file failed to open would you? I agree that the failbit should be set when open() fails. But I think what Steve Terry is saying is that when the second open() succeeds it should unset the failbit. It is a new file, essentially a new instance of the whole fstream thing, and nothing has gone wrong yet - so the failbit should have been unset. ----------- |
|
|