I was under the impression that fstream worked the same way as printing to the screen, but that does not seem to be the case. I recently had a function that I wrote to the screen. When I changed it to write to a file, it did not write the file in the right order, even when I had it do both at the same time. As far as I can tell, the problem comes from it being a recursive function, and the data was being held in the stream until the file was closed, instead of being written right away. I was able to fix it by moving the close function to right after the print statement, anyway.
Could someone give me an explanation on how this actually works? I am also wondering if it would not be better to move the open function to right before the print statement.
The data is buffered by the stream so it is not always outputted right away, because it can be inefficient. To make sure that everything you have written is outputted you can flush the stream.
outfile.flush()
or
outfile << std::flush;
If you use std::endl instead of '\n' it will also flush the stream.
outfile << std::endl;
Note that the file stream is always flushed automatically when the stream is closed.
I think std::cout is automatically flushed when you use std::cin so I guess you are less likely to notice this when using std::cout.
I never thought of flushing the stream, but that works fine, and let me just pass the stream as an argument, so I can simply avoid all the opening and closing of the file, and do it before and after the function call.
I am a bit confused about your explanation of the console stream though. When I stepped through it, the console was written to right away, no std::cin involved. The first node was written to the file more or less right away, but the second one was not written until after the third node, and those two were backwards. Which what made me think to move the close function.
Anyway, I probably would not have noticed the bit about the file stream if it was not for the recursion. :-)