Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Closing a QFile in use.

    General and Desktop
    qfile qiodevice
    3
    4
    2664
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • NIXIN
      NIXIN last edited by

      I am writing to a .csv file as below:

      QString fileName = "someFile.csv";

      QFile file(fileName);

      if(file.exists())
      file.remove();

      if(file.open(QIODevice::WriteOnly | QIODevice::Truncate)
      {
      //write something to file as comma separated string

      file .close();
      }

      Above code is working fine.

      But when file is already opened (double click and open the file from the path where it is created), and I run my application, data is not being written to the file. Earlier data exists.

      How can I fix this?

      ALso is it possible to close the file if it is already opened (double click and open the file from the path where it is created), programmatically.

      1 Reply Last reply Reply Quote 0
      • m.sue
        m.sue last edited by

        Hi,
        you are working on WINDOWS I assume.

        On WINDOWS it is possible to open a file for writing that another app already has open for reading if the other app opened the file with the OF_SHARE_DENY_NONE option or similar, which is not the default. So all in all it depends on the other app where you may not have the controll over (i.e. source from).

        You can close files (handles) opened by other apps only with elevated rights.
        -Michael.

        1 Reply Last reply Reply Quote 3
        • mrjj
          mrjj Lifetime Qt Champion last edited by

          Hi
          The normal case for this is to check the return code of open and if it fails
          output a message to user that file is locked.
          http://doc.qt.io/qt-5/qfiledevice.html#error

          m.sue 1 Reply Last reply Reply Quote 3
          • m.sue
            m.sue @mrjj last edited by

            @mrjj said in Closing a QFile in use.:

            output a message to user that file is locked

            Yes, as the other app would most certainly crash if it suddenly works on a file handle that was closed from outside.
            -Michael.

            1 Reply Last reply Reply Quote 1
            • First post
              Last post