How to know that a file was opened ? QT

我的梦境 提交于 2019-12-10 17:47:40

问题


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

Any idea please!!!


回答1:


2 solutions:

  • Using 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

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.

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.

  • Using system 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...



来源:https://stackoverflow.com/questions/12841309/how-to-know-that-a-file-was-opened-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!