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

后端 未结 7 1377
傲寒
傲寒 2020-11-27 05:16

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

相关标签:
7条回答
  • 2020-11-27 05:52

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 05:57

    You can try to open the file. If it failed, it means not exist in most time.

    0 讨论(0)
  • 2020-11-27 06:03

    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?

    0 讨论(0)
  • 2020-11-27 06:04

    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]);
       }
    }
    
    0 讨论(0)
  • 2020-11-27 06:06

    How about simply:

    #include <io.h>
    if(_access(path, 0) == 0)
        ...   // file exists
    
    0 讨论(0)
  • 2020-11-27 06:08

    Another option: 'PathFileExists'.

    But I'd probably go with GetFileAttributes.

    0 讨论(0)
提交回复
热议问题