How can we check if a file Exists or not using a Win32 program? I am working for a Windows Mobile App.
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;
}
You can try to open the file. If it failed, it means not exist in most time.
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 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]);
}
}
How about simply:
#include <io.h>
if(_access(path, 0) == 0)
... // file exists
Another option: 'PathFileExists'.
But I'd probably go with GetFileAttributes
.