Checking if a file is in use without try catch?

前端 未结 4 1943
一向
一向 2020-12-18 23:09

Is there a way I can check if a file is in use or is not opened by other process without just trying to open it and catching an exception? Is there no service method to test

4条回答
  •  忘掉有多难
    2020-12-19 00:04

    Interesting way to avoid try catch (but implies an attempt to open) is the LockFile() or CreateFile() functions:

    HANDLE WINAPI CreateFile(...)

    If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot.

    If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.


    BOOL WINAPI LockFile(...)

    If the function succeeds, the return value is nonzero (TRUE).

    If the function fails, the return value is zero (FALSE). To get extended error information, call GetLastError.

    This locks the specified file for exclusive access by the calling process, and on failure writes error information to the thread's last-error, which can be retreived using the GetLastError function.

    It would still be thinkable that between the unlockFile and OpenFile another process could lock the file, but it possible to minimize this period by keeping the file locked just to the moment it needs to be opened.

提交回复
热议问题