windows 我们如何使用 Win32 程序检查文件是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3828835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:38:44  来源:igfitidea点击:

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

windowswinapifile

提问by Krishnan

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

我们如何使用 Win32 程序检查文件是否存在?我正在为 Windows Mobile 应用程序工作。

采纳答案by Preet Sangha

You can call FindFirstFile.

你可以打电话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]);
   }
}

回答by Zach Burlingame

Use GetFileAttributesto check that the file system object exists and that it is not a directory.

使用GetFileAttributes检查文件系统对象存在,它不是一个目录。

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?

复制自如何用 C 语言检查 Windows 上是否存在目录?

回答by codaddict

You can make use of the function GetFileAttributes. It returns 0xFFFFFFFFif the file does not exist.

您可以使用该功能GetFileAttributes0xFFFFFFFF如果文件不存在则返回。

回答by Pierre

How about simply:

简单地说:

#include <io.h>
if(_access(path, 0) == 0)
    ...   // file exists

回答by Adrian McCarthy

Another option: 'PathFileExists'.

另一种选择: 'PathFileExists'

But I'd probably go with GetFileAttributes.

但我可能会和GetFileAttributes.

回答by fanzhou

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

您可以尝试打开该文件。如果失败,则表示大部分时间不存在。

回答by Alturis

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