views:

67

answers:

2

I'm having problems with the getline instruction from fstream. this is a snippet from my code:


boolean_1=true;
while(true)
{
   if(boolean_1)
   {
      //some stuff
   }
   else
   {
        save_file.open("save.txt", fstream::in);
        //some stuff
        save_file.close();
   }

    mission_file.open(filename, fstream::in);
    mission_file.getline(buffer_line, 256);

    //some other stuff

    boolean_1=false;
    save_file.open("save.txt", fstream::out);
    //write something
    save_file.close();    
}

This code should open the mission_file the first time it runs, and open a save file at the next iteration. The save file is created at the end of every cycle. At least it should work like this. Because, the first time everything works flawlessly, but in the next iteration, "mission_file.getline(buffer_line, 256);" returns an empty line, making the program crash. Also, if boolean_1 starts as false, the cycle works fine until the next one.

I have already checked the existence of the required ".txt"s, both mission_file and save_file return is_open() true.

A: 

Are you making sure that mission_file is being closed, because I don't see mission_file.close(). Or is it that you just missed to put that line in the code snippet here.

rtdecl
Sorry, i forgot to put the mission_file.close() in the snippet, anyway it's in the code.
Tibor
+1  A: 

It's impossible to see from the code extracts that you've posted but it sounds like you are re-using the same std::fstream object for each cycle.

It would be clearer to create a new local object inside the loop at the point at which you need to re-open the file.

If you must re-use the same fstream object to open a new file (or the same file another time) you must make sure to clear any stream error flags before reading from the new file.

Performing a clear at some point before the first read from the new file should do this.

mission_file.clear()
Charles Bailey
Thank you very much, .clear() resolved everything :) !
Tibor