QFile Append mode weird behavior

  • Hello. I am using QFile and QTextStream to append lines to a local file on lubuntu linux. I open the file at different times, only same thread. For example user interaction causes modification on this file at 10am then below code works. And at 10.20 am same thing and so on.

    Somehow there are many \00\00\00\00.... bytes written in my files, unfortunately sometimes. It is very interesting that the same problem occurs in log files created by QsLog also which we didnt wrote. Anyway, Here is my code snippet.

        QFile localFile("/home/foo/bar.txt");
        bool hasLocal = localFile.open(QIODevice::Append);
        if (!hasLocal){
            return 0;
        if (localFile.size()==0)//SIFIR DOSYA
            QLOG_WARN() << "New bar.txt created at  " << localPath;
        QTextStream localOut(&localFile);
        Business::applyTextCodec(&localOut);//actually stream->setCodec(QTextCodec::codecForName("CP857");
        for (int i=0;i<lines->size();i++){
            if (lines->at(i).trimmed().isEmpty())
            QString tmp = QString("1,").append(QString::number(startLineNumber++).rightJustified(5,'0')).append(",");
            localOut << tmp;
        QApplication::processEvents();//not sure to do this
        QApplication::processEvents();//not sure to do this

    Any ideas?

  • Moderators

    @Hjunior Those 0 bytes could come from Unicode characters - are you writing Unicode?
    You could add

    qDebug() << tmp;

    to your loop to see in the console what you're writing into the file.

  • No. All of the strings i write is ENGLISH chars.

    And the \00 bytes are appended after my append finished and file closed. I mean i write 5 lines (Block A). No problem. Then 2 minutes later i open the file again and write some lines again (Block B) and so on (Block C,D,E). At this point i realized sometimes some \00 chars appended before i reopen it. Like;
    A B \00\00\00... C D E F \00\00 G H....

  • Lifetime Qt Champion


    Did you try to print the line content before you pass it to the stream ?

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.