Categories: Uncategorized

Check whether a file is open or not in Win32

There is no easy way to check file is open. I write simple code to check it but it still has problems.

  1. Like thread, it is not sure the file is actually open or not at the function returns because file is global resource, any other processes can open or close at any moment.
  2. This blocks other process to open file it would succeed if this function not operate.
enum ISFILEOPEN {
 ISFILEOPEN_NO,
 ISFILEOPEN_YES,
 ISFILEOPEN_UNKNOWN,
} ;

ISFILEOPEN IsFileOpen(LPCTSTR pFile);
#include 
#include "IsFileOpen.h"

ISFILEOPEN IsFileOpen(LPCTSTR pFile)
{
 HANDLE f = CreateFile(
  pFile,
  GENERIC_READ,
  0, // share
  NULL, // sec
  OPEN_EXISTING,
  FILE_ATTRIBUTE_NORMAL,
  NULL);

 if(f==INVALID_HANDLE_VALUE)
 {
  switch(GetLastError())
  {
  case ERROR_SHARING_VIOLATION:return ISFILEOPEN_YES;
  case ERROR_ACCESS_DENIED:return ISFILEOPEN_UNKNOWN;
  }
  return ISFILEOPEN_NO;
 }

 CloseHandle(f);
 return ISFILEOPEN_NO;
}
admin

Recent Posts

Obtain global IP in bash

In current Internet environment, every PC is assigned a private IP. If global IP is…

3 years ago

Create log file in the directory of the script in Python

__file__ is the script file itself. From python3.9 above, it is an absolute path, otherwise…

3 years ago

RichTextBox’s font changes automatically in C#

You need to clear these two flags IMF_DUALFONT and IMF_AUTOFONT to keep font unchanged.

3 years ago

Test post to check image URL

This is an image inserted by wordpress 'Add Media'

3 years ago

msbuild says ‘target does not exist’

I don't know what is going wrong but... How to fix it Open the solution…

3 years ago

Creating a break point that hits on calling win32 api

Create a break point that hits when CreateProcess was called Enter a Function Breakpoint Enter…

4 years ago