【发布时间】:2011-04-19 05:37:46
【问题描述】:
我们如何使用 Win32 程序检查文件是否存在?我正在为 Windows Mobile 应用工作。
【问题讨论】:
-
std::filesystem::exists() C++17 以上
我们如何使用 Win32 程序检查文件是否存在?我正在为 Windows Mobile 应用工作。
【问题讨论】:
您可以使用函数GetFileAttributes。如果文件不存在,则返回0xFFFFFFFF。
【讨论】:
INVALID_FILE_ATTRIBUTES。在 64 位上,它可能是 0xFFFFFFFFFFFFFFFF。
DWORD,它怎么能返回0xFFFFFFFFFFFFFFFF?
您可以拨打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() 好多了。
GetFileAttributes 是一个班轮
file = "*",即使没有名为*的文件,这也可能返回true
使用GetFileAttributes 检查文件系统对象是否存在并且它不是目录。
BOOL FileExists(LPCTSTR szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
!(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
【讨论】:
GetFileAttributes()可能会因为文件不存在以外的错误条件返回INVALID_FILE_ATTRIBUTES。
您可以尝试打开文件。如果失败,说明大部分时间都不存在。
【讨论】:
另一个选项:'PathFileExists'。
但我可能会选择GetFileAttributes。
【讨论】:
PathFileExists需要使用“Shlwapi.dll”(在一些windows版本上不可用)并且比GetFileAttributes稍慢。
另一种更通用的非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)。
简单地说:
#include <io.h>
if(_access(path, 0) == 0)
... // file exists
【讨论】:
遇到了同样的问题,并在另一个使用GetFileAttributes 方法的forum 中找到了这个简短的代码
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 文档:
| Value | Meaning |
|---|---|
| OF_EXIST (0x00004000) | Opens a file and then closes it. Use this to test for the existence of a file. |
见文档: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-openfile
【讨论】: