delete_this_account
delete_this_account

Reputation: 2446

printf flush problem

I am modifying a big C code. For test purposes I had to redirect stdout to a file. I used this code snipped for this purpose: fp=freopen("OUT", "w" ,stdout) Now all printf calls will write to fp. It is a big code so I do not want to search all of the exit points and close the file before each exit. What happens if do not close the file? Is there a way to make it autoflush each time I write something to the file?

Upvotes: 0

Views: 877

Answers (2)

paxdiablo
paxdiablo

Reputation: 882136

setvbuf is probably the way to go:

setvbuf (fp, NULL, _IONBF, 0);

This will turn off buffering altogether. Just be prepared for the inevitable performance hit.

You also need to be aware that this will flush only at the runtime-library level in many systems, it will not necessarily cause a flush to the storage medium, as the UNIX fsync(fileno(fp)) would try to do.

So, while it will be okay if your program crashes, it will not help if the whole OS falls in a screaming heap. But then you probably have bigger problems than losing a little bit of output :-)


But, unless your program is crashing, you probably shouldn't worry about it. ISO C99 says, in part, that one of the actions of exit(), and hence returning from main(), is:

Next, all open streams with unwritten buffered data are flushed, all open streams are closed, ...

So your data will be output regardless in that case.

Upvotes: 4

C. K. Young
C. K. Young

Reputation: 223133

Yes. Use setvbuf with _IONBF:

setvbuf(stdout, 0, _IONBF, 0);

Upvotes: 1

Related Questions