Krishna
Krishna

Reputation: 21

How to check if a file is open

I need to check if any files in a folder is open by other applications or not. Unfortunately, if a file is open, the GetFileAttributesA() return wrong values. Is there a workaround for this or am I doing something wrong ?

Upvotes: 2

Views: 1316

Answers (1)

John Knoeller
John Knoeller

Reputation: 34128

GetFileAttributes has nothing to do with file sharing. The only way to know if someone has the file open (thereby preventing you from opening it) is to try an open it yourself.

bool IsFileOpenBySomeoneElse(LPCTSTR pszFilename)
{
    HANDLE hfile = CreateFile(pszFilename, 
                              GENERIC_READ /*| GENERIC_WRITE*/, 
                              0, //0 is share-none
                              NULL,
                              OPEN_ALWAYS);
    if (hfile != INVALID_HANDLE_VALUE)
    {
       CloseHandle(hfile);
       return false;
    }
    return (GetLastError() == ERROR_SHARING_VIOLATION);
}   

But writing this function does you no good, because by the time you get around to opening th e file for processing, some other application may have the file open.

The only safe way to do this is to go ahead an do what you intend to do with the file, and when you try and open it for processing, notice the error value if you fail. Once you have the file open, you must keep it open until you are done or some other process can open it (or delete it!) behind your back.

Upvotes: 1

Related Questions