I'm having a little problem with QFile. I write a small log file during a process, but due to the performance (at least I think so) I don't close the file after each write, but only at the end. Instead, I use .flush() , but when the programme crashes, the file is completely empty.
Does anyone know what the reason could be? I would not like to open and close the file before and after each write process, as I am running processes every millisecond and do not want to impair performance too much.
Classname::Classname() {
m_LoggingPath = "cameraLogging_"+QDateTime::currentDateTime().toString("dd_MM_yy hh_mm_ss")+".txt";
m_LoggingFile.setFileName(m_LoggingPath);
m_LoggingFile.open(QIODevice::Append);
m_LoggingStream.setDevice(&m_LoggingFile);
}
Classname::~Classname() {
m_LoggingFile.close();
}
void Classname::logAction(QString action, QString data){
m_LoggingStream << QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss.zzz")
<< " Action: " << action
<< " Data: " << data
<< " \n ";
m_LoggingStream.flush();
m_LoggingFile.flush();
}
Normally OS doesn't write files instantly. Instead all writes are buffered for certain amount. Especially if the media is something like SSD or Flash. For the latter small writes result in rewriting whole file allocation block or two adjacent, which usually ranges between 512 and 4096 bytes. Small writes reduce life of flash disks by pinpoint writes.
For similar reasons on some OSes and file systems metadata of file, i.e. it's size and, may be not updated until file is closed.
It's a good idea either to use OS-provided API or facilities for logging or use a mature logging library instead of dancing on same old garden rakes every time.