Reputation: 105
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.
Upvotes: 1
Views: 6448
Reputation: 791869
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()
Upvotes: 2
Reputation: 674
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.
Upvotes: 0