C++ - 确定Linux中是否存在目录(不是文件)

Met*_*ark 23 c++ linux directory exists

如何确定Linux中是否存在使用C++的目录(不是文件)?我尝试使用stat()函数,但在找到文件时返回正数.我只想查找输入的字符串是否是目录,而不是其他内容.

One*_*One 29

根据man(2)stat,您可以在st_mode字段上使用S_ISDIR宏:

bool isdir = S_ISDIR(st.st_mode);
Run Code Online (Sandbox Code Playgroud)

另外,如果您的软件可以在其他操作系统上运行,我建议使用Boost和/或Qt4来简化跨平台支持.


ayu*_*ush 16

我在这里找到的东西怎么样

#include <dirent.h>

bool DirectoryExists( const char* pzPath )
{
    if ( pzPath == NULL) return false;

    DIR *pDir;
    bool bExists = false;

    pDir = opendir (pzPath);

    if (pDir != NULL)
    {
        bExists = true;    
        (void) closedir (pDir);
    }

    return bExists;
}
Run Code Online (Sandbox Code Playgroud)

或者使用stat

struct stat st;
if(stat("/tmp",&st) == 0)
    if(st.st_mode & S_IFDIR != 0)
        printf(" /tmp is present\n");
Run Code Online (Sandbox Code Playgroud)

  • 你需要使用DarkDust的额外`和`条件更新底部.`(myStat.st_mode)&S_IFMT)== S_IFDIR)`.谢谢DarkDust. (3认同)

Dr *_*r G 10

如果你可以查看boost文件系统库.这是以通用和可移植的方式处理此类问题的好方法.

在这种情况下,使用就足够了:

#include "boost/filesystem.hpp"   
using namespace boost::filesystem; 
...
if ( !exists( "test/mydir" ) ) {bla bla}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,你需要下载并安装boost ...但我怀疑你会后悔:) (3认同)

Dar*_*ust 6

我理解你的问题的方式是:你有一条路径,比方说,/foo/bar/baz(baz是一个文件),你想知道是否/foo/bar存在.如果是这样,解决方案看起来像这样(未经测试):

char *myDir = dirname(myPath);
struct stat myStat;
if ((stat(myDir, &myStat) == 0) && (((myStat.st_mode) & S_IFMT) == S_IFDIR)) {
    // myDir exists and is a directory.
}
Run Code Online (Sandbox Code Playgroud)