Search code examples
qtfileconcurrencylockingread-write

Qt: How to lock/prevent a file from being read while it is written?


I am using Qt5 on Windows 7.
In my current project I open a binary file in order to populate it with data coming from a TCP socket. Normally, after the file is populated, I close it and another application will read this binary file for further processing.
Well, the problem is: The writing operation takes about 4-5 seconds (or even more) so I need to find a way to prevent the other application from reading from the binary file until the file is completely populated...
Here below is the code (yet I suppose it won't help much):

int error = 0;
unsigned long dataLength;
char dataBuffer[1500];
QFile localFile("datafile.bin");
//
localFile.open(QIODevice::WriteOnly);
while(error == 0)
{
    error = readSocket(dataBuffer, &dataLength);
    if(error == 0)
    {
        localFile.write(dataBuffer, dataLength);
    }
    else
    {
        error = -1;
    }
}
localFile.close();

I am thinking about using a temporary file and rename it after the write operation is complete.
But maybe there is another better/smarter idea? Some kind of "lock file for reading" maybe...?


Solution

  • If you have the source to both applications, then the one writing the file can signal the other application by one of many IPC mechanisms (e.g. local sockets) that it has finished writing.

    Alternatively, write to a file with a different filename and then rename / copy the file to the location expected by the reading application, when the write has finished.

    However, it is advisable to use QSaveFile, rather than QFile when writing out files. As the documentation states: -

    While writing, the contents will be written to a temporary file, and if no error happened, commit() will move it to the final file

    So this will likely solve the problem for you.