Fopen / fclose effectiveness

Typically, most products implement a log file mechanism. What is the best practice of writing a debug log file in terms of fopen / fclose performance. Does a file pointer open (if the log is turned on) - is it a good option or frequent open and closed file pointers every time an operator needs to be written to a log file?

+4
source share
4 answers

Ideally, you should not close the log file to the end. Typically, many products also have a β€œcrash handling” mechanism that will be called up anyway before the application terminates. This will be the best place to close the log file.

For windows you can check SetUnhandledExceptionFilter

+2
source

This usually depends on which file you are interacting with. Of course, binaries should be open while reading. You can parse text into a string and close the file immediately if the file is plain text.

I would like to say that you should keep the file pointer open for the entire life of the program, but if you encounter a crash, it will never be closed. Then I suggest leaving it open during relatively safe operations and low-risk operations, but always open / close it when you partially relate to the stability of the application. No one wants file pointers to remain open. :)

0
source

Based on the comment you can use fstream . Just open ofstream at the beginning and it will be closed when the program ends. Using fstream instead of C-style fopen / close makes it a lot easier, since it follows the RAII principle, so you don't have to worry about closing the file. There is probably no reason to close the file manually and open it every time you want to write something. If you do not want to write to the same file from another program at the same time, opening and closing the file periodically is just a waste of time and code.

0
source

Usually I write to memory (a variable) and write it only once when the application ends. Of course, this will not bring much benefit if the application crashes, or you need to read the log while the program is running, but for me this is usually not a problem, and the performance is higher. I think it depends on your needs.

0
source

Source: https://habr.com/ru/post/1333005/


All Articles