Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 可移植测试C+中的文件夹+;?_C++_Stat_Dirent.h - Fatal编程技术网

C++ 可移植测试C+中的文件夹+;?

C++ 可移植测试C+中的文件夹+;?,c++,stat,dirent.h,C++,Stat,Dirent.h,我的基本问题是,这段代码几乎总是引发异常: bool DirectoryRange::isDirectory() const { struct stat s; stat(ep->d_name, &s); #if defined(__linux__) if((S_ISDIR(s.st_mode) != 0) != (ep->d_type == DT_DIR)) { throw std::logic_error("Director

我的基本问题是,这段代码几乎总是引发异常:

bool DirectoryRange::isDirectory() const
{
    struct stat s;
    stat(ep->d_name, &s);

#if defined(__linux__)
    if((S_ISDIR(s.st_mode) != 0) != (ep->d_type == DT_DIR))
    {
        throw std::logic_error("Directory is not directory");
    }
#endif

    return S_ISDIR(s.st_mode);
}

bool DirectoryRange::isFile() const
{
    struct stat s;
    stat(ep->d_name, &s);

#if defined(__linux__)
    if((S_ISREG(s.st_mode) != 0) != (ep->d_type == DT_REG))
    {
        throw std::logic_error("File is not file");
    }
#endif

    return S_ISREG(s.st_mode);
}
检查dirent值不是便携的,而是得到正确的答案;虽然stat是错误的,但它是可移植的


那么,如果stat似乎不起作用,我如何能够便携式地检查目录呢?

对于初学者来说,
S_ISDIR
是:

如果测试为真,则宏的计算结果为非零值,如果测试为真,则为0 测试是错误的

S_ISDIR(m)-目录测试

(我的重点)。对
bool
的显式强制转换是错误的,并且没有完成任何有用的操作。正确使用此宏(以及其他
S..
宏)的方法是:

 if(S_ISDIR(s.st_mode) == 0)
 {
      throw std::logic_error("Directory is not a Directory");
 }

这似乎是最可靠的:

bool DirectoryRange::isDirectory() const
{
#if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__))
    return ep->d_type == DT_DIR;
#else 
    auto path = syspath();
    DIR * dp = opendir(path.c_str());
    if(dp) closedir(dp);
    return dp;
#endif
}

bool DirectoryRange::isFile() const
{
#if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__))
    return ep->d_type == DT_REG;
#else 
    auto path = syspath();
    FILE * fp = fopen(path.c_str(), "r");
    if(fp) fclose(fp);
    return fp;
#endif
}

尝试一下Boost.Filesystem.Minor迂腐的琐事,但并非所有文件系统都有文件夹的概念。特别是大型机,它没有。希望你永远都不需要知道这一点,但以防万一。。。好吧,就是这样。我做了一些改变,但没有解决它;无论如何,我在添加异常之前注意到了这个错误,因为它试图将文件作为文件夹打开。