Qt:如何在写入文件时锁定/防止文件被读取? [英] Qt: How to lock/prevent a file from being read while it is written?

查看:72
本文介绍了Qt:如何在写入文件时锁定/防止文件被读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Windows 7上使用Qt5.
在我当前的项目中,我打开一个二进制文件以便用来自TCP套接字的数据填充它.通常,在填充文件后,我将其关闭,然后另一个应用程序将读取此二进制文件以进行进一步处理.
好吧,问题是:写入操作大约需要4-5秒(甚至更多),因此我需要找到一种方法防止其他应用程序从二进制文件读取直到文件完全填充 ...
下面是代码(不过我想这不会有太大帮助):

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...?

推荐答案

如果您同时拥有两个应用程序的源代码,则编写该文件的应用程序可以通过许多IPC机制(例如本地套接字)之一向另一个应用程序发出信号:完成写作.

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.

但是,建议在编写时使用 QSaveFile ,而不要使用QFile.出文件.如文档所述:-

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

写入时,内容将被写入一个临时文件,如果没有错误发生,则commit()会将其移动到最终文件中

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.

这篇关于Qt:如何在写入文件时锁定/防止文件被读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆