QFile: Append mode does not work well.



  • Hi guys,

    I met a problem when i use QFile in Append mode.
    here is the code:
    @#include <QtCore/QCoreApplication>
    #include <QFile>
    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);

    QFile file&#40;"C:/test.txt"&#41;;
    bool ret;
    file.open(QIODevice::WriteOnly);
    file.write("this is string 1.");
    file.close();
    file.open(QIODevice::Append);
    file.write("this is string 2.");
    file.close();
    
    return a.exec&#40;&#41;;
    

    }@

    the problem is that, string 2 can not be writen in correct pos. acctually, when i open the file with QIODevice::Append, the pos of the file is always at the begining, even i use seek() to adjust the pos.

    and a good news is that, if i use a new instance of QFile to open same file with Append mode, it works well.
    i am really confused.



  • Have you tried:
    @file.open( QIODevice::WriteOnly | QIODevice::Append );@
    on your second opening of the file ?



  • [quote author="Landy" date="1349686182"]Hi guys,

    the problem is that, string 2 can not be writen in correct pos.
    [/quote]

    Hi, I can't reproduce this problem under Windows using Qt4.8 and Qt5.0.



  • I tried. it didn't work.
    [quote author="rcari" date="1349686786"]Have you tried:
    @file.open( QIODevice::WriteOnly | QIODevice::Append );@
    on your second opening of the file ?[/quote]



  • I am using static version of Qt4.7.4 and IDE is VS2010.
    it's really strange that u can't reproduce this problem.
    i hope this is not caused by Qt version.
    [quote author="1+1=2" date="1349745527"][quote author="Landy" date="1349686182"]Hi guys,

    the problem is that, string 2 can not be writen in correct pos.
    [/quote]

    Hi, I can't reproduce this problem under Windows using Qt4.8 and Qt5.0.
    [/quote]



  • Oh, Seems that you have been misused "QIODevice::Append" flag.

    bq. QIODevice::Append 0x0004 The device is opened in append mode, so that all data is written to the end of the file.

    If you don't always want to append contents to the end of the file, you should not use this flag. In other words, if your need QIODevice::Append, you won't care position and seek() etc.

    Debao



  • Acctually, as u see, i didn't use position or seek() in my code.
    i really wanna append contents to the end of the file, but it didn't work to use QIODevice::Append flag.


Log in to reply
 

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