如何知道文件已打开?QT [英] How to know that a file was opened ? QT

查看:116
本文介绍了如何知道文件已打开?QT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道用户是否打开了文件以进行读取(双击或使用...打开),经过研究,我正在Windows上使用Qt Creator编写 C ++ 应用程序找到了 QFileSystemWatche ,但只有在发生更改时,它才让我知道特定的文件夹.

I want to know if a file was opened by user for reading (double click or open with ...), I am coding a C++ application with Qt Creator on Windows, after some research I found QFileSystemWatche, but it let me know only if a change was happened in the specific folder.

void QFileSystemWatcher :: fileChanged(const QString& path)[signal]当指定路径的文件位于修改,重命名或从磁盘中删除.

void QFileSystemWatcher::fileChanged ( const QString & path ) [signal] This signal is emitted when the file at the specified path is modified, renamed or removed from disk.

如何知道该文件是否已打开?还是有一种在打开或关闭文件时修改文件的方法?

How to know if the file was opened? or is there a way to modify a file when it is opened or closed?

有什么主意!!!

推荐答案

2个解决方案:

  • 使用Qt

您可以执行以下功能(伪代码):

You can make the following function (pseudocode):

function is_open(file)
    handle = open file to write
    if(handle is ok)
        close file
        return true
    else
        return false

然后您每秒调用一次,并且每当 is_open(t-1)== false&&时发出一个信号 fileOpened(const QString& file).is_open(t)== true ,其中 t 是时间.

Then you call it once per second, and emit a signal fileOpened(const QString& file) whenever is_open(t-1) == false && is_open(t) == true, where t is the time.

但是,此解决方案可能很慢,并且可能导致io-access膨胀,尤其是在文件位于远程服务器上的情况下.它还可能会导致磁盘/SSD提前磨损,因此我不建议您使用此解决方案.

However, this solution might be slow, and can result is some io-access bloat, especially if the file is on a distant server. It can also cause a premature wear of the disk/SSD, so I'm not recommending this solution.

  • 使用系统API

您可以获取所有进程的所有文件句柄的列表,然后检查它是否包含要监视的文件的句柄.同样,您必须每秒执行x次此操作.它将减慢您的电脑的速度;实际上,它不是真正可移植的(所需的代码在很大程度上取决于特定于系统的API),并且可能需要提高特权才能工作.我也不建议这么做...

You can get get the list of all file handles of all processus, then checking if it contains a handle to the file you want to monitor. Again, you will have to do this x times per second. It will slow your pc; it is not really portable in practice (the code needed heavily depends on system-specific API), and it might need elevated priviledge to work. I don't recommend that too...

这篇关于如何知道文件已打开?QT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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