Qt provides the
QFile[
^] class that can be used with together with the
QTextStream[
^] class .
But it is not really necessary to use the Qt classes. You can just use the C or C++ standard library file I/O functions to create a file or open an existing one and write to it.
To write formatted text to files, I still prefer the C library functions
fopen
,
fclose
, and
fprintf
because formatting is quite simple with
fprintf
.
I usually create a class to implement logging and use an instance of that class in the main application module (e.g. the
QMainWindow
derived class with Qt applications).
Such a class would typical implement functions to open, close, and write to the file. The write functions may accept strings or even a format string with variable arguments like
printf
using
va_list[
^]. The write functions may also prefix the output with a time stamp. This can be optionally controlled by a parameter to the functions. It is also common to have a log level parameter and a corresponding member variable. So only those messages are logged where the passed level is below or equal to the member variable.
If you have many log operations in short intervals you should not close the log file after writing to it but let it stay open until the application terminates. However, when doing so the file may get corrupted when your application crashes.
[EDIT] Correction: The file usually gets not corrupted but the recent outputs will be not present.