在Windows C应用程序中,我想验证传递给函数的参数,以确保指定的路径存在.*
如何在C中检查Windows上是否存在目录?
*我知道你可以进入竞争条件,在你检查存在的时间和使用它不再存在的路径的时间之间,但我可以处理.
当权限发挥作用时,明确知道目录是否存在可能会变得棘手.在尝试确定目录是否存在时,该进程可能无权访问目录或父目录.这可以满足我的需求.如果目录不存在或者我无法访问它,则在我的应用程序中都将两者视为无效路径故障,因此我不需要区分.如果您的解决方案提供此区别,则(虚拟)奖励积分.
C语言,C运行时库或Win32 API中的任何解决方案都很好,但理想情况下我想坚持常用的库(例如kernel32,user32等)并避免涉及加载非标准库的解决方案(如Shlwapi.dll中的PathFileExists).如果您的解决方案是跨平台的,那么(虚拟)奖励积分.
ret*_*one 90
做这样的事情:
BOOL DirectoryExists(LPCTSTR szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
Run Code Online (Sandbox Code Playgroud)
的GetFileAttributes()方法被包括在Kernel32.dll中.
dar*_*mos 23
这是一个完全与平台无关的解决方案(使用标准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;
}
Run Code Online (Sandbox Code Playgroud)
特定于Windows的实现,支持MBCS和UNICODE构建:
#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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
61612 次 |
最近记录: |