[C++] How to check if a file is used by another process ?



  • Hi everyone,

    I have an app that write in a file (txt), and another reading it, when it's updated.
    i.e : [app 1] > (write) > [.txt] > (is read by) > [app 2]

    QFileSystemWatcher allows to be noticed when a file is changed.

    I want to read the file once the writing is finished, but QFileSystemWatcher sends signals during the modification.

    I try to solve this by using QLockFile, to catch if the file is still using by another process, for waiting to read the file. But it's not working as expecting.

    bool App1::write(const QString filePath, const QString data) {
            QLockFile lockFile(filePath);
            QFile file(filePath);
            if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
                return false;
            }
            lockFile.lock();
            QTextStream out(&file);
            out << data;
            lockFile.unlock();
            return true;
    }
    

    This doesn't work, app crashes. Help please !

    Regards,



  • Uhm, you say you want to read the file but in your code snippet you write the file...?

    AFAIR there is no native way to check whether a file is still opened or not. You can get notified about changes, but how shall the QFileSystemWatcher know that there will be no further changes in the future?



  • @micland, yes thanks. I have re-edited the post.

    It's may send when the following operation

    out << data; 
    

    is finished.

    The issue is: file is something read before the writing operation is completed. I want to prevent this. :/



  • This post is deleted!


  • @Johan_R28
    I don't know if there is a native way to solve your problem but I think you should read all data and extend your buffer (or process the new data) when a modification was detected. There is no "fileFinallyChanged" signal.
    If you have both processes under control you could also try to sync them using a separate IPC (The writing process tells the reading process that the work is done) or by writing the data to a preliminary, temporary file that will be renamed after the file is complete so the reading process will not "see" while the generating is still in progress (just one of many possible ways - the best solution depends on your needs).


Log in to reply
 

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