How can we check if a file Exists or not using Win32 program?
Use GetFileAttributes
to check that the file system object exists and that it is not a directory.
BOOL FileExists(LPCTSTR szPath){ DWORD dwAttrib = GetFileAttributes(szPath); return (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));}
Copied from How do you check if a directory exists on Windows in C?
You can make use of the function GetFileAttributes
. It returns 0xFFFFFFFF
if the file does not exist.
You can call FindFirstFile
.
Here is a sample I just knocked up:
#include <windows.h>#include <tchar.h>#include <stdio.h>int fileExists(TCHAR * file){ WIN32_FIND_DATA FindFileData; HANDLE handle = FindFirstFile(file, &FindFileData) ; int found = handle != INVALID_HANDLE_VALUE; if(found) { //FindClose(&handle); this will crash FindClose(handle); } return found;}void _tmain(int argc, TCHAR *argv[]){ if( argc != 2 ) { _tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]); return; } _tprintf (TEXT("Looking for file is %s\n"), argv[1]); if (fileExists(argv[1])) { _tprintf (TEXT("File %s exists\n"), argv[1]); } else { _tprintf (TEXT("File %s doesn't exist\n"), argv[1]); }}