Reputation: 659
Normally, Most of the product has log file mechanism implemented. What is the best practice to write debug log file in terms of fopen / fclose performance. Does keeping file pointer open (if logger is enable) is good option or frequent open and close file pointers every time when some statement need to write into log file ?
Upvotes: 4
Views: 4894
Reputation:
I usually log to memory (a variable), and only write it to file once, when the app finishes. Of course, this won't do much good if the app crashes, or you need to read the log while the program is running, but that is not usually a problem for me, and the performance is superior. Depends on your needs, I guess.
Upvotes: 0
Reputation: 13471
Based on the comment that you can use fstream
. Just open an ofstream
at the beginning and it will get closed when the program ends. Using fstream
instead of C-style fopen/close make a lot of things easier as it conforms to the RAII principle, so you do not have to worry about file closing. There is probably no reason to close the file manually and open it again every time you want to log something. If you don't want to write to the same file from another program at the same time, opening and closing the file periodically is just waste of time and code.
Upvotes: 0
Reputation: 14900
Ideally, you shouldn't close the log file until the end. Usually many products also have some "crash handling" mechanism, that would be called in any case before application terminates. This will be the best place to close the logfile.
For windows, you can check SetUnhandledExceptionFilter
Upvotes: 2
Reputation: 1388
Usually, it depends on what kind of file you're interacting with. Binary files must be open while reading, of course. You can parse text into a string and close the file right away if the file is plain text.
I'd like to say you should keep the file pointer open during the whole program lifetime, but in the case you experience a crash, it'll never get closed. Then I will suggest keeping it open during relatively safe and low-risk operations, but open/close it constantly when you're partial on the application's stability. Nobody wants file pointers left open. :)
Upvotes: 0