如何检查文件是否存在或不使用 Win32程序?

如何检查文件是否存在或不使用 Win32程序?我正在为一个 Windows 手机应用程序工作。

91230 次浏览

您可以使用函数 GetFileAttributes。如果文件不存在,它返回 0xFFFFFFFF

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

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

BOOL FileExists(LPCTSTR szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);


return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
!(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}

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

您可以尝试打开该文件。如果失败,则意味着在大多数时间内不存在。

另一个选择: “ PathFileExists”

但我可能会选 GetFileAttributes

另一种更通用的非窗口方式:

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

简单地说:

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

遇到同样的问题,发现这个简短的代码在另一个 论坛使用 获取文件属性方法

DWORD dwAttr = GetFileAttributes(szPath);
if (dwAttr == 0xffffffff){


DWORD dwError = GetLastError();
if (dwError == ERROR_FILE_NOT_FOUND)
{
// file not found
}
else if (dwError == ERROR_PATH_NOT_FOUND)
{
// path not found
}
else if (dwError == ERROR_ACCESS_DENIED)
{
// file or directory exists, but access is denied
}
else
{
// some other error has occured
}


}else{


if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
{
// this is a directory
}
else
{
// this is an ordinary file
}
}

其中 szPath是文件路径。

使用 OpenFileuStyle = OF_EXIST

if (OpenFile(path, NULL, OF_EXIST) == HFILE_ERROR)
{
// file not found
}
// file exists, but is not open

请记住,当使用 OF_EXIST时,在 OpenFile成功后文件不会打开:

价值 意思是
OF _ EXIST (0x00004000) 打开一个文件,然后关闭它。使用此命令测试文件是否存在。

请参阅文档: Https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-openfile