如何在C中检查Windows上是否存在目录?

Zac*_*ame 63 c windows winapi

在Windows C应用程序中,我想验证传递给函数的参数,以确保指定的路径存在.*

如何在C中检查Windows上是否存在目录?

*我知道你可以进入竞争条件,在你检查存在的时间和使用它不再存在的路径的时间之间,但我可以处理.

附加背景

当权限发挥作用时,明确知道目录是否存在可能会变得棘手.在尝试确定目录是否存在时,该进程可能无权访问目录或父目录.这可以满足我的需求.如果目录不存在或者我无法访问它,则在我的应用程序中都将两者视为无效路径故障,因此我不需要区分.如果您的解决方案提供此区别,则(虚拟)奖励积分.

C语言,C运行时库或Win32 API中的任何解决方案都很好,但理想情况下我想坚持常用的库(例如kernel32,user32等)并避免涉及加载非标准库的解决方案(如Shlwapi.dll中的PathFileExists).如果您的解决方案是跨平台的,那么(虚拟)奖励积分.

有关

我们如何使用Win32程序检查文件是否存在?

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中.

  • 如果 szPath 是 `"C:\\"`,GetFileAttributes、PathIsDirectory 和 PathFileExists 将不起作用。 (3认同)

dar*_*mos 23

这是一个完全与平台无关的解决方案(使用标准C库)

编辑:对于这个在Linux中编译,替换<io.h><unistd.h>_accessaccess.对于真正的平台无关解决方案,请使用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)

  • 这不是平台无关的或标准的,那就是微软对POSIX的模仿(实际上你会从`<unistd.h>`得到`access`而它不会以下划线开头.) (4认同)
  • 正确的,它不是POSIX,在其他平台上没有`io.h`或`_access`(带下划线)这样的东西. (2认同)

Sim*_*ier 9

如果您可以链接到Shell轻量级API(shlwapi.dll),则可以使用PathIsDirectory函数.


Gre*_*reg 5

另一种选择是外壳函数 PathFileExists()

PathFileExists() 文档

此函数“确定文件系统对象(例如文件或目录)的路径是否有效。”