代码之家  ›  专栏  ›  技术社区  ›  RK-

我们如何检查文件是否存在,或者不使用win32程序?

  •  65
  • RK-  · 技术社区  · 15 年前

    我们如何检查文件是否存在,以及是否使用win32程序?我正在为一个Windows Mobile应用程序工作。

    7 回复  |  直到 8 年前
        1
  •  22
  •   cdonts    10 年前

    你可以打电话 FindFirstFile .

    这是我刚做的一个样本:

    #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]);
       }
    }
    
        2
  •  187
  •   Community Mohan Dere    9 年前

    使用 GetFileAttributes 检查文件系统对象是否存在,以及它是否为目录。

    BOOL FileExists(LPCTSTR szPath)
    {
      DWORD dwAttrib = GetFileAttributes(szPath);
    
      return (dwAttrib != INVALID_FILE_ATTRIBUTES && 
             !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
    }
    

    抄袭 How do you check if a directory exists on Windows in C?

        3
  •  32
  •   Ajay    8 年前

    你可以利用这个功能 GetFileAttributes . 它返回 0xFFFFFFFF 如果文件不存在。

        4
  •  16
  •   Pierre    11 年前

    简单地说:

    #include <io.h>
    if(_access(path, 0) == 0)
        ...   // file exists
    
        5
  •  7
  •   Adrian McCarthy    13 年前

    另一种选择: 'PathFileExists' .

    但我可能会同意 GetFileAttributes .

        6
  •  1
  •   fanzhou    14 年前

    您可以尝试打开文件。如果失败了,就意味着大多数时候都不存在。

        7
  •  -1
  •   Alturis    11 年前

    另一种更通用的非Windows方式:

    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;
    }