我如何使用Win32程序检查文件是否存在?我正在为Windows Mobile应用程序工作。
使用GetFileAttributes
来检查文件系统对象是否存在且不是目录。
BOOL FileExists(LPCTSTR szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
!(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
从如何在C中检查Windows上的目录是否存在?复制而来:
GetFileAttributes()
可能由于文件不存在以外的错误条件而返回 INVALID_FILE_ATTRIBUTES
。 - Jonathan Wood您可以使用函数GetFileAttributes
。如果文件不存在,它会返回0xFFFFFFFF
。
DWORD
,它如何返回 0xFFFFFFFFFFFFFFFF
? - Ajay您可以调用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]);
}
}
FindClose
函数了。而且你不能从一个 void 函数中返回值。 - David HeffernanGetFileAttributes()
更好。 - trojanfoeGetFileAttributes
是一行代码。 - Matt Clarksonfile = "*"
, 即使没有名为 * 的文件,这可能会返回 true
。 - Felix Dombek那么我们可以简单地这样做:
#include <io.h>
if(_access(path, 0) == 0)
... // file exists
PathFileExists
需要使用 "Shlwapi.dll"(在某些 Windows 版本中不可用),并且比 GetFileAttributes
稍微慢一些。 - Bitterblue我遇到了同样的问题,在另一个论坛中找到了这段简短的代码,使用了GetFileAttributes方法。
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
是文件路径。
OpenFile
函数并设置 uStyle
参数为 OF_EXIST
。if (OpenFile(path, NULL, OF_EXIST) == HFILE_ERROR)
{
// file not found
}
// file exists, but is not open
记住,在使用OF_EXIST
时,文件在OpenFile
成功后不会打开。根据Win32文档:
值 | 含义 |
---|---|
OF_EXIST (0x00004000) | 打开一个文件然后关闭它。使用此选项来测试文件是否存在。 |
请参阅文档: https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-openfile
你可以尝试打开文件。如果失败了,那通常意味着文件不存在。
另一种更通用的非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;
}
_access(0)
。 - Rob K