问题
在Windows C应用程序中,我要验证传递给函数的参数,以确保指定的路径存在。*
如何在C中检查上是否存在目录?
*我理解你可以进入竞态条件,在你检查存在的时间和你使用路径不再存在的时间之间,但我可以处理这一点。
附加背景
当权限开始发挥作用时,明确知道目录存在或不存在可能会变得棘手。在尝试确定目录是否存在时,进程可能没有访问该目录或父目录的权限。这对我的需求来说是可以的。如果该目录不存在或者我无法访问它,这两种情况在我的应用程序中都会被视为无效路径故障,因此我不需要进行区分。(虚拟)奖励积分(如果您的解决方案提供此区别)。
C语言、C运行时库或Win32应用程序接口中的任何解决方案都可以,但理想情况下,我希望坚持使用通常加载的库(例如kernel32、user32等)。并避免涉及加载非标准库的解决方案(如Shlwapi.dll中的PathFileExists )。同样,如果你的解决方案是跨平台的,(虚拟)加分。
相关
How can we check if a file Exists or not using Win32 program?
发布于 2011-06-03 02:07:36
这样做:
BOOL DirectoryExists(LPCTSTR szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
GetFileAttributes()方法包含在Kernel32.dll中。
发布于 2011-06-03 02:06:57
这是一个完全与平台无关的解决方案(使用标准C库)
Linux:要在中编译,请将<io.h>
替换为<unistd.h>
,将_access
替换为access
。要获得真正的平台无关性解决方案,请使用Boost FileSystem库。
#include <io.h> // For access().
#include <sys/types.h> // For stat().
#include <sys/stat.h> // For stat().
bool DirectoryExists( const char* absolutePath ){
if( _access( absolutePath, 0 ) == 0 ){
struct stat status;
stat( absolutePath, &status );
return (status.st_mode & S_IFDIR) != 0;
}
return false;
}
支持MBCS和UNICODE构建的特定于Windows的实现:
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <tchar.h>
BOOL directory_exists( LPCTSTR absolutePath )
{
if( _taccess_s( absolutePath, 0 ) == 0 )
{
struct _stat status;
_tstat( absolutePath, &status );
return (status.st_mode & S_IFDIR) != 0;
}
return FALSE;
}
发布于 2013-03-23 15:37:14
如果您可以链接到Shell轻量级API (shlwapi.dll),则可以使用PathIsDirectory function。
https://stackoverflow.com/questions/6218325
复制相似问题