File Handling?

how can i get rid of constantly opening and closing file?
1
2
3
4
5
6
while(1)
{
 //open file
 //get key pressed
 //write it to file
 //close file 

please provide a little sample code, someone told me to store it to buffer and flush the buffer. what you think?
If you're going to write to it again, just don't close it.
well, the contents will never be saved then..
you see if i open the file and write to it in a while(1) loop.. the file will never be closed and i will lose whatever i wrote..
Here's the clever bit; do all your writing in some loop, and when it's time for the program to finish, right before it finishes, close the file.
Could also flush/sync whenever you wanna write to the file.

http://www.cplusplus.com/doc/tutorial/files/

Bottom of the page.
you mean i can do this
1
2
3
4
5
6
7
//open file
while(1)
{
//write to file
//syncy()
}
//close file 
That explains why I just answered the same question. Check your other thread, it's answered there.
thanks for your help, the other thread is not mine.
would you please guide me,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <fstream>
#include <iostream>
using namespace std;
#include <windows.h>

int main () {
	
	ofstream outfile ("test.txt");
	int count=0;
	int x;
	
	while(1)
	{
		Sleep(10);
		cin>>x;
		outfile<<x;
		count++;
		
		if(count==15)
		{
			count=0;
			outfile.flush();
		}
	}
	
	outfile.close();
	
	return 0;
}

is it okay to flush this way?
Well, does it work? If so, then it's probably ok :) I don't see anything that's gonna cause your computer to blow up.

In all reality, the call to flush isn't even necessary. It gets called on it's own when the buffer gets full, or the stream closes. But, I think it's more of a safety thing, in case the program crashes for some reason.
Yes it works fine, i am thinking about flushing the stream after specific time intervals for safety because i can never be sure when the buffer gets full.
thank you for your help sir.
Topic archived. No new replies allowed.