如何检查是否使用目录存在C++和WINAPI
可能重复:
How do you check if a directory exists on Windows in C?如何检查是否使用目录存在C++和WINAPI
如何检查是否使用C++和Windows API目录是否存在?
好吧,我们都在n0obs在某个时间点。询问没问题。下面是一个简单的函数,它正是这样做的:
#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',那么它确实不存在。但是,如果它返回大多数其他错误,那么实际上在指定的路径上存在某些内容,但这些属性根本无法访问。 –
对于那些在这个答案的绊脚石,请记住,上面的代码是ANSI而不是Unicode。对于现代的Unicode,最好在这个其他的*答案中使用LPCTSTR参数,如片段:http://*.com/a/6218445。 (LPCTSTR将被编译器转换为'wchar_t *')。然后,您可以将该识别Unicode的函数包装成一个C++'std :: wstring'而不是'std :: string'。 – JasDev
0.1秒谷歌搜索:
BOOL DirectoryExists(const char* dirName) {
DWORD attribs = ::GetFileAttributesA(dirName);
if (attribs == INVALID_FILE_ATTRIBUTES) {
return false;
}
return (attribs & FILE_ATTRIBUTE_DIRECTORY);
}
此代码可能工作:如果链接到外壳轻量级API
//if the directory exists
DWORD dwAttr = GetFileAttributes(str);
if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY))
也许你可以显示你到目前为止 –
为什么不只是做=========> BOOL PathFileExists(pszPath);
Fractal