dev c++ - Trying to open a file that doesn't exist prevents subsequent opening in dev-C++ -


i trying execute simple piece of code in dev-c++:

int fflag, num; char nomefile[40]; fstream str;  fflag=0; while (fflag==0)       {       cout<<"\nfile name? ";       cin>>nomefile;       str.open(nomefile,ios::in);        //checking if file exists       if (str)          {          fflag=1;          str>>num;             // reading value , sending standard output          cout<<num<<"\n";          }       else          {          cout<<"\nfile doesn't exist! ";          }        } 

if try open existing file, there no problem. if try open file doesn't exist, receive error message (file doesn't exist) subsequent trial open existing file (i mean in same loop) fail producing same error message.

i tried add close instruction after detecting not-existing file, doesn't solve problem. don't understand! seems that, if try open not existing file, subsequent retrial (with str.open) returns null pointer, if file exists.

the same code execute correctly in code::blocks, should issue regarding dev-c++ or maybe problem of software portability.

any help? lot! giancarlo perlo - italy

failure open sets "fail" bit. these bits never(!) reset automatically, must reset them manually using clear(). bit counterintuitive considering fact opening new file should erase earlier history, consistent throughout iostream api.

in order fix this, move fstream loop though, each file gets opened new fstream instance. in general, should move declaration of variables close use possible. example, int fflag; should bool successful_read = false;, declared before loop. makes clearer how used. otoh, use endless loop break after reading file. further, use std::string name , use getline(std::cin, name) read file name.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -