天天看點

檢查某個檔案或目錄是否存在的函數

RT

#include <Windows.h>

BOOL FileExists(LPCTSTR lpszFileName, BOOL bIsDirCheck)
{
	//試圖取得檔案屬性
	DWORD dwAttributes = ::GetFileAttributesA(lpszFileName);
	if ( INVALID_FILE_ATTRIBUTES == dwAttributes)
	{
		return FALSE;
	}

	//是目錄
	if (dwAttributes & FILE_ATTRIBUTE_DIRECTORY)
	{
		if (bIsDirCheck) //目前檢測的也是目錄
		{
			return TRUE;
		}
		else	
			return FALSE;
	}
	else //是檔案
	{
		if (bIsDirCheck)
		{
			return FALSE;
		}
		else	
			return TRUE;
	}
	
}

int main(int argc, char *argv[])
{
	BOOL bRetDir, bRetFile;
	//測試,一個目錄
	bRetDir = FileExists("C:\\11\\", TRUE);
	//測試, 一個檔案
	bRetFile = FileExists("C:\\11\\1.xls", FALSE);	
	return 0;
}