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;
}

Leave a comment

Your email address will not be published. Required fields are marked *