How can we check if a file Exists or not using Win32 program?

Viewed 89831

How can we check if a file Exists or not using a Win32 program? I am working for a Windows Mobile App.

9 Answers

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.

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://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-openfile

Related