bill
bill

Reputation: 51

Trouble saving data written to a file when I kill the app

My program is always writing data to a file but when I close it before the program fully stops, the end result is nothing being written to the file. I would really like to be able to close it without completing it fully, so how can I fix this to make it constantly saving the file?

ofstream outfile;
outfile.open("text.txt", std::ios::app);
bool done = false;
int info;
  while (done == false){
    cin>>info;
    outfile<<info;
    cout<<info<<"Choose different info";
       if(info == 100){
         done = true;
       }
  }
outfile.close();

This is obviously just an example, but it is very similar to my actual code.

Edit: When i say closing I mean killing it (Hitting red X at top right of console)

Upvotes: 0

Views: 328

Answers (2)

MyNick
MyNick

Reputation: 556

The operation system doesn't write to the file when you call the write function to save time, it wait to check if you want to write anything else or for a time which will be "good" to write. You write to a buffer and the operating system will write this buffer to the file. When you close the function it write anything that left in the buffer to the file. You can force your code to write to the file using flush method. Just flush your file after every time you write and you will be ok. flush: http://www.cplusplus.com/reference/ostream/ostream/flush/

outfile << n;
outfile.flush();

Upvotes: 5

chwarr
chwarr

Reputation: 7202

You likely need to flush your std::ofstream when you have done "enough" work.

"enough" work here is going to depend on your application.

Perhaps

...
outfile<<info;
outfile.flush();
...

Upvotes: 5

Related Questions