简体   繁体   中英

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?

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.

Yes. Use setvbuf with _IONBF :

setvbuf(stdout, 0, _IONBF, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM