Open and closing output file multiple times during a program.

Just trying to wrap my head around this. I have a large menu driven program and I need to keep a log of all activities.

The general layout:

Switch (x){
Case:
function x()
Case:
function y()
}

function x{
Case:
function z()
Case:
function a()
}.

It is basically a series of switch statements that make calls to functions with other switch statements. As it sits right now I am passing the reference value of my output file to my functions, so I can collect everything that goes on. The problem is the outfile only gets written to once I close the file. To guard against a program crash and losing all my data, I was wondering if I could keep opening and closing the SAME ouput file and writing data to it.

Basic question is can I keep opening, closing, and writing to the output file without overwriting my previous data? thanks
Did you try calling yourFile.flush();?

http://www.cplusplus.com/reference/iostream/ostream/flush/
Last edited on
I have never heard of that function, but it looks like it will solve my problem. Thank you very much!
Have a follow up question. I have only used ofstream and ifstream. If I open my output file using fstream, does that mean I could have a function search through this file without opening it?
fstream can open a file in input or output modes, or both. But it sti gets opened. How would you be able to read/write without opening it?
I think I confused myself. I was thinking I needed to close/open my output file to search through it, but I guess as long as it's open it doesn't matter if it is input or ouput.
My goal is to be able to search through my logs while they are still open to recieve data.

I have only searched through files I have just opened and I thought that was the way it was always going to be done. thanks
Topic archived. No new replies allowed.