Checking whether a file exists

There is no API function that checks whether a file exists in the file system, but it's possible to create a simple function that can check if file exists, and there is even more than one method to to that.
The following 3 functions check whether a file exists in the system, and each function do it in different method:

  • IsFileExist1: We try to open the file, if we get a valid hanle, the file exists.
  • IsFileExist2: We try to find the file by using the FindFirstFile API function. if we get a valid hanle, the file exists.
  • IsFileExist3: We try to get the attributes of the file. If the function fails, and returns 0xffffffff value, the file doesn't exist.
Also, be aware that the first function works only for filenames, but not for folders. the other 2 functions (IsFileExist2 and IsFileExist3) also works properly with folders.

Return back to C/C++ code index

BOOL IsFileExist1(LPSTR lpszFilename)
{
	HANDLE hFile = CreateFile(lpszFilename, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);	
	if (hFile != INVALID_HANDLE_VALUE)
	{
		CloseHandle(hFile);
		return TRUE;
	} else
	{
		return FALSE;
	}
}


BOOL IsFileExist2(LPSTR lpszFilename)
{
	WIN32_FIND_DATA wfd;

	HANDLE hFind = FindFirstFile(lpszFilename, &wfd);
	if (hFind == INVALID_HANDLE_VALUE)
		return FALSE;
	else
	{
		FindClose(hFind);
		return TRUE;
	}
}

BOOL IsFileExist3(LPSTR lpszFilename)
{
	DWORD dwAttr = GetFileAttributes(lpszFilename);
	if (dwAttr == 0xffffffff)
		return FALSE;
	else 
		return TRUE;
}