问题描述
这是一个仅适用于Windows的程序,因此便携式代码不是问题.
我需要:
bool DoesFileExist( LPWSTR lpszFilename ) { // ... }
推荐答案
在Windows代码中有两种常见的方法. getfileattributes和createfile,
bool DoesFileExist(LPCWSTR pszFilename) { DWORD dwAttrib = GetFileAttributes(pszFilename); if ( ! (dwAttrib & FILE_ATTRIBUTE_DEVICE) && ! (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) { return true; } return false; }
这将告诉您一个文件,但是它不会告诉您是否可以访问该文件.为此,您需要使用CreateFile.
bool DoesFileExist(LPCWSTR pszFilename) { HANDLE hf = CreateFile(pszFilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE != hf) { CloseHandle(hf); return true; } else if (GetLastError() == ERROR_SHARING_VIOLATION) { // should we return 'exists but you can't access it' here? return true; } return false; }
但请记住,即使您从其中一个呼叫中获得了正确的态度,也可能在打开它时仍然不存在该文件.很多时候,最好只是表现得好像文件存在并在没有文件时优雅地处理错误.
其他推荐答案
根据尊贵的雷蒙德·陈(Raymond Chen),您应该如果您迷信.
,请使用getfileattributes其他推荐答案
使用_access或stat.
问题描述
This is for a Windows-only program so portable code is not an issue.
I need simply:
bool DoesFileExist( LPWSTR lpszFilename ) { // ... }
推荐答案
There are two common ways to do this in Windows code. GetFileAttributes, and CreateFile,
bool DoesFileExist(LPCWSTR pszFilename) { DWORD dwAttrib = GetFileAttributes(pszFilename); if ( ! (dwAttrib & FILE_ATTRIBUTE_DEVICE) && ! (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) { return true; } return false; }
This will tell you a file exists, but but it won't tell you whether you have access to it. for that you need to use CreateFile.
bool DoesFileExist(LPCWSTR pszFilename) { HANDLE hf = CreateFile(pszFilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE != hf) { CloseHandle(hf); return true; } else if (GetLastError() == ERROR_SHARING_VIOLATION) { // should we return 'exists but you can't access it' here? return true; } return false; }
But remember, that even if you get back true from one of these calls, the file could still not exist by the time you get around to opening it. Many times it's best to just behave as if the file exists and gracefully handle the errors when it doesn't.
其他推荐答案
According to the venerable Raymond Chen, you should use GetFileAttributes if you're superstitious.
其他推荐答案
What’s the best way to check if a file exists in C++? (cross platform)
Use _access or stat.