Reading and writing same file



  • Hi,
    I log some data from my application to QFile (via QTextStream).

    Sometimes I want to read all data in the file and display them. How to do it (at the same time, the file must be still opened for writing)?



  • QIODevice::ReadWrite should do the trick...check out the documentation on QFile and QIODevice.

    Not really sure how you are going to read the file while writing to it at the same time, kinda be a mess, but you can open it for ReadWrite access


  • Moderators

    @MartinD I would not read/write at the same time as it will most probably cause problems. If you want to read close the file, open it for reading, read the content, close it, open for writing again.



  • This post is deleted!


  • Thanks, I will close the file momentarily, read it, and then reopen it for append.



  • Hi,

    As said by @jsulm and @ndt_mike , while doing file operations
    Once u open the file either for reading the data or writing the data.
    Use file.close(); .
    Once u finished reading the data or writing the data, and for the next operations u can open the file and do the further necessary operations,then again use file.close();

    Link to how to use QFile for reading and writing data.

    http://doc.qt.io/qt-5/qfile.html

    And here is the link the enum values which will be used.

    http://doc.qt.io/qt-4.8/qiodevice.html#OpenModeFlag-enum



  • Since a file is seekable I'd exploit this feature. Open the file in QIODevice::ReadWrite then

    const qint64 pos = file.pos(); //Save the current position
    file.seek(0);  // move back to beginning of the file
    // read what you need
    file.seek(pos); // go back to where you were before reading
    

Log in to reply
 

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