【发布时间】:2012-01-04 06:03:22
【问题描述】:
如何使用 C++ 和 windows API 检查目录是否存在?
【问题讨论】:
-
为什么不直接像msdn.microsoft.com/en-us/library/windows/desktop/…那样做
BOOL PathFileExists(pszPath);?
如何使用 C++ 和 windows API 检查目录是否存在?
【问题讨论】:
BOOL PathFileExists(pszPath);?
这是一个简单的函数,它就是这样做的:
#include <windows.h>
#include <string>
bool dirExists(const std::string& dirName_in)
{
DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
【讨论】:
GetFileAttributes() 在发生故障时返回INVALID_FILE_ATTRIBUTES。你必须使用GetLastError() 来找出失败的真正原因。如果它返回ERROR_PATH_NOT_FOUND、ERROR_FILE_NOT_FOUND、ERROR_INVALID_NAME 或ERROR_BAD_NETPATH,那么它确实不存在。但如果它返回大多数其他错误,那么在指定路径中确实存在某些东西,但属性根本无法访问。
wchar_t*。)。然后,您可以包装该 Unicode 感知函数以采用 C++ std::wstring 而不是 std::string。
如果你可以链接到 shell 轻量级 API (shlwapi.dll),你可以使用PathIsDirectory function
【讨论】:
此代码可能有效:
//if the directory exists
DWORD dwAttr = GetFileAttributes(str);
if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY))
【讨论】:
0.1 秒谷歌搜索:
BOOL DirectoryExists(const char* dirName) {
DWORD attribs = ::GetFileAttributesA(dirName);
if (attribs == INVALID_FILE_ATTRIBUTES) {
return false;
}
return (attribs & FILE_ATTRIBUTE_DIRECTORY);
}
【讨论】: