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?
I am modifying a big C code. For test purposes I had to redirect
Share
setvbufis probably the way to go: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 frommain(), is:So your data will be output regardless in that case.