Should log file streams be opened/closed on each write or kept open during a desktop application’s lifetime?

If you have frequent read/writes it is more efficient to keep the file open for the lifetime with a single open/close.

You might want to flush periodically or after each write though. If your application crashes you might not have all the data written to your file. Use fflush on Unix-based systems and FlushFileBuffers on Windows.

If you are running on Windows as well you can use the CreateFile API with FILE_FLAG_NO_BUFFERING to go direct to the file on each write.

It is also better to keep the file open for the lifetime, because each time you open/close you might have a failure if the file is in use. For example, you might have a backup application that runs and opens/closes your file as it’s backing it up. And this might cause your program to not be able to access your own file. Ideally, you would want to keep your file open always and specify sharing flags on Windows (FILE_SHARE_READ). On Unix-based systems, sharing will be default.

Leave a Comment