How can we check if a file Exists or not using a Win32 program? I am working for a Windows Mobile App.
9 Answers
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?
- 1
 - 1
 
- 13,476
 - 14
 - 56
 - 65
 
- 
                    7+1 because of a short code example. Code examples are a time saver to get started. – nalply Mar 11 '12 at 14:41
 - 
                    I would like to note that your function returns bool and not BOOL. – Marius Bancila Aug 26 '12 at 20:02
 - 
                    
 - 
                    Does this also deliver the best performance in file existence checking ? – Bitterblue Apr 05 '13 at 11:51
 - 
                    1
 - 
                    
 - 
                    2Although it is possible that `GetFileAttributes()` might return `INVALID_FILE_ATTRIBUTES` due to error conditions other than the file does not exist. – Jonathan Wood Feb 24 '17 at 21:19
 - 
                    
 - 
                    
 
You can make use of the function GetFileAttributes. It returns 0xFFFFFFFF if the file does not exist.
- 
                    17Interesting history on GetFileAttributes and why it is the preferred method in Windows code by Raymond Chen: http://blogs.msdn.com/b/oldnewthing/archive/2007/10/23/5612082.aspx – Zach Burlingame Jun 02 '11 at 18:04
 - 
                    2
 - 
                    12Actually it returns `INVALID_FILE_ATTRIBUTES` if the file not exists. On 64-bit it could be `0xFFFFFFFFFFFFFFFF`. – Andreas Spindler Apr 09 '13 at 17:14
 - 
                    7@AndreasSpindler, Since the return type is `DWORD` how it can return `0xFFFFFFFFFFFFFFFF` ? – Ajay Dec 19 '16 at 10:58
 - 
                    2Updated link to Raymond Chen's blog: https://devblogs.microsoft.com/oldnewthing/20071023-00/?p=24713 – Ray Jul 25 '20 at 13:42
 
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]);
   }
}
- 9,304
 - 4
 - 46
 - 72
 
- 64,563
 - 18
 - 145
 - 216
 
- 
                    You forgot to call `FindClose`. And you can't return a value from a void function. – David Heffernan Dec 19 '12 at 19:26
 - 
                    4Half corrected. You need to check for FILE_ATTRIBUTE_DIRECTORY. – David Heffernan Dec 19 '12 at 22:53
 - 
                    2See other answers for better ways to do this. Also, the code won't even compile as-is due to argv[1] being used in fileExists(); – Christian Aichinger Feb 11 '13 at 14:38
 - 
                    3
 - 
                    2
 - 
                    4Suppose `file = "*"`, this might return `true` even if there isn't a file called * – Felix Dombek Feb 28 '14 at 12:43
 
How about simply:
#include <io.h>
if(_access(path, 0) == 0)
    ...   // file exists
- 4,114
 - 2
 - 34
 - 39
 
- 
                    
 - 
                    2@Buddhika Chaturanga I started using it in Borland Turbo C, back in the 80's. It was the only way to check for the presence of a file, before the fancier "CreateFile". It's buried in the Visual Studio documentation. – Pierre Jul 04 '18 at 12:43
 - 
                    I had to use if (_waccess(path.c_str(), 0) == 0)... works like a charm for folders and files, thank you @Pierre – mourad Nov 16 '22 at 07:53
 
Another option: 'PathFileExists'.
But I'd probably go with GetFileAttributes.
- 45,555
 - 16
 - 123
 - 175
 
- 
                    2In addition `PathFileExists` requires the use of "Shlwapi.dll" (which is unavailable on a few windows versions) and is slightly slower than `GetFileAttributes`. – Bitterblue Apr 05 '13 at 12:45
 - 
                    
 - 
                    BTW, PathFileExists is just a wrapper for GetFileAttributes with additional SetErrorMode(SEM_FAILCRITICALERRORS) wrapper. – Alex Sep 09 '19 at 17:17
 
Came across the same issue and found this brief code in another forum which uses GetFileAttributes Approach
DWORD dwAttr = GetFileAttributes(szPath);
if (dwAttr == 0xffffffff){
  DWORD dwError = GetLastError();
  if (dwError == ERROR_FILE_NOT_FOUND)
  {
    // file not found
  }
  else if (dwError == ERROR_PATH_NOT_FOUND)
  {
    // path not found
  }
  else if (dwError == ERROR_ACCESS_DENIED)
  {
    // file or directory exists, but access is denied
  }
  else
  {
    // some other error has occured
  }
}else{
  if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
  {
    // this is a directory
  }
  else
  {
    // this is an ordinary file
  }
}
where szPath is the file-path.
- 544
 - 7
 - 15
 
You can try to open the file. If it failed, it means not exist in most time.
- 97
 - 1
 - 5
 
- 
                    
 - 
                    7A file open can also fail if the files exists but the user does not have sufficient privileges to open the file. These days, that's a **very** common situation. – JackLThornton Apr 15 '16 at 23:39
 - 
                    Not to mention it is not the cheapest because the file can be on a network share which adds latency for each call and with CloseHandle you have two calls instead of one. – Igor Levicki Nov 22 '19 at 10:37
 
Use OpenFile with uStyle = OF_EXIST
if (OpenFile(path, NULL, OF_EXIST) == HFILE_ERROR)
{
    // file not found
}
// file exists, but is not open
Remember, when using OF_EXIST, the file is not open after OpenFile succeeds. Per Win32 documentation:
| Value | Meaning | 
|---|---|
| OF_EXIST (0x00004000) | Opens a file and then closes it. Use this to test for the existence of a file. | 
See doc: https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-openfile
- 21
 - 1
 - 6
 
Another more generic non-windows way:
static bool FileExists(const char *path)
{
    FILE *fp;
    fpos_t fsize = 0;
    if ( !fopen_s(&fp, path, "r") )
    {
        fseek(fp, 0, SEEK_END);
        fgetpos(fp, &fsize);
        fclose(fp);
    }
    return fsize > 0;
}
- 74
 - 8
 
- 
                    if you're going to use fopen et al. you may as well just use `_access(0)`. – Rob K Jun 22 '16 at 14:10
 - 
                    2@RobK This has the minor advantage of being cross-platform whereas _access is not. The real problem is that it will return that zero-length files don't exist... – Perkins Sep 05 '18 at 19:00
 - 
                    fopen_s is Microsoft specific, and in addition to 0 byte files being declared non-existing by this broken code it also fails on files it can't open (permissions, sharing). – Igor Levicki Nov 22 '19 at 10:39