Joe
Joe

Reputation: 16831

How do I check whether a file exists in C++ for a Windows program?

This is for a Windows-only program so portable code is not an issue.

I need simply:

bool DoesFileExist( LPWSTR lpszFilename )
{
    // ...
}

Upvotes: 3

Views: 5075

Answers (12)

efotinis
efotinis

Reputation: 14961

According to the venerable Raymond Chen, you should use GetFileAttributes if you're superstitious.

Upvotes: 13

McAden
McAden

Reputation: 13972

This should do it.

#include <fstream>

bool DoesFileExist( LPWSTR lpszFilename )
{
  ifstream fin;
  fin.open(lpszFilename.c_str(), ifstream::in);
  fin.close();
  return !fin.fail();
}

Upvotes: 0

Kornel Kisielewicz
Kornel Kisielewicz

Reputation: 57525

Windows only? Use GetFileAttributes:

bool DoesFileExist( LPWSTR lpszFilename )
{
  return GetFileAttributes( lpszFilename ) != INVALID_FILE_ATTRIBUTES;
}

Or the more strict version (as per Szere Dyeri's comment):

bool DoesFileExist( LPWSTR lpszFilename )
{
  return ( ( GetFileAttributes( lpszFilename ) != INVALID_FILE_ATTRIBUTES )
         && ( GetLastError() == ERROR_FILE_NOT_FOUND ) );
}

Upvotes: 3

John Knoeller
John Knoeller

Reputation: 34128

There are two common ways to do this in Windows code. GetFileAttributes, and CreateFile,

bool DoesFileExist(LPCWSTR pszFilename)
{
   DWORD dwAttrib = GetFileAttributes(pszFilename);
   if ( ! (dwAttrib & FILE_ATTRIBUTE_DEVICE) &&
        ! (dwAttrib & FILE_ATTRIBUTE_DIRECTORY))
   {
      return true;
   }
   return false;
}

This will tell you a file exists, but but it won't tell you whether you have access to it. for that you need to use CreateFile.

bool DoesFileExist(LPCWSTR pszFilename)
{
    HANDLE hf = CreateFile(pszFilename,
                           GENERIC_READ,
                           FILE_SHARE_READ | FILE_SHARE_WRITE,
                           NULL,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,
                           NULL);

    if (INVALID_HANDLE_VALUE != hf)
    {
        CloseHandle(hf);
        return true;
    }
    else if (GetLastError() == ERROR_SHARING_VIOLATION)
    {
        // should we return 'exists but you can't access it' here?
        return true;
    }

    return false;
}

But remember, that even if you get back true from one of these calls, the file could still not exist by the time you get around to opening it. Many times it's best to just behave as if the file exists and gracefully handle the errors when it doesn't.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941218

Open it. You can't reliably test if a file exists on a multi-tasking operating system. When you open it you can make sure it doesn't disappear.

Upvotes: 4

Jerry Coffin
Jerry Coffin

Reputation: 490018

Here's one of many options:

HANDLE handle = FindFirstFile(lpszFilename);
if (handle == INVALID_HANDLE_VALUE) 
    return false;
FindClose(handle);
return true;

Upvotes: 1

Roger Nelson
Roger Nelson

Reputation: 1912

In my experience, _access() is simple and fairly portable

#if defined(__MSDOS__) || defined(_Windows) || defined(_WIN32)
    bool file_exists =  _access(file_name,0) == 0;
#endif
#ifdef unix
    bool file_exists =  _access(file_name,F_OK) == 0;
#endif

Upvotes: 0

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 247899

I usually use boost::filesystem. Has an exists() function. :)

Upvotes: -1

Walter Bright
Walter Bright

Reputation: 4307

GetFileAttributes is what you're looking for. If it returns a value that is not INVALID_FILE_ATTRIBUTES the file exists.

Upvotes: 5

JaredPar
JaredPar

Reputation: 754515

This is a bit more of a complex question. There is no 100% way to check for existence of a file. All you can check is really "exstistence of a file that I have some measure of access to." With a non-super user account, it's very possible for a file to exist that you have no access to in such a way that access checks will not reveal the existincae of an file.

For instance. It's possible to not have access to a particular directory. There is no way then to determine the existence of a file within that directory.

That being said, if you want to check for the existence of a file you have a measure of access to use one of the following: _stat, _stat64, _stati64, _wstat, _wstat64, _wstati64

Upvotes: 7

Matt Dillard
Matt Dillard

Reputation: 14853

I use the FindFirstFile / FindNextFile API functions for this purpose.

Upvotes: 0

Related Questions