11/25/2007

Check File Existence on Windows Platform

There are several ways to accomplish this:

1. Use _access() in CRT.
#include <io.h>
if
( _access(filename, 0) == 0 )
{
  
// file exists
}
2. Use GetFileAttributes() in Win32 or stat() in POSIX(Win32 has _stat()).
if (INVALID_FILE_ATTRIBUTES != GetFileAttributes(fileName))
{
   // file exists
}

3. Just create it and check the returned error code, using CreateDirectory() or CreateFile() in Win32.
HANDLE hFile = NULL;
hFile = CreateFile(fileName, 0, 0, NULL, CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE, NULL);
if ( hFile == INVALID_HANDLE_VALUE)
{
  if (GetLastError() == ERROR_ALREADY_EXISTS)
  {
    // file exists
  }
}
else
{
  CloseHandle(hFile);
}

4. Use FindFirstFile() in Win32.
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile(fileName, &wfd);
if (hFind != INVALID_HANDLE_VALUE)
{
  CloseHandle(hFind);
  // file exists
}

5. Use other C++ file stream/file system library
  5.1 try open() on fstream in STL, if not exists, it will fail.
  5.2 try Boost library: boost::filesystem::exists(fileName)

But be careful about the atomic semantic and race condition. If you want to check the file's existence and then do some operation with that file(such as open for read/write), solution NO.3 is best for you.

No comments: