How to know that a file was opened ? QT

2.3k views Asked by At

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

There are 1 answers

3
Synxis On

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