为什么opendir()随机导致ENOENT?

时间:2014-06-25 22:57:51

标签: c++ linux c++11 opendir

要在Linux Ubuntu上检索目录的内容(递归),我使用以下RAII结构:

struct L_DirectoryReader
{
    //Fields
    L_PathData pathData;
    DIR *dirHandle;
    struct dirent *currentDirEntry;

    //Method declaration happens before constructor,
    //because it is used in the constructor.
    void readDir()
    {
        errno = 0;
        this->currentDirEntry = readdir(this->dirHandle);

        //Error checking
        if(errno != 0)
        {
            int errorcode = errno;
            switch(errorcode)
            {
                default:
                {
                    throw os3util::fileh::exc::FileIOException(
                        std::string("Failed to retrieve contents of dir:")
                        + kNEWLINE_STR + this->pathData.relativePath.getFullPath()
                        + kNEWLINE_STR + "with readdir() errorcode "
                        + os3util::strfunc::intToString(errorcode)
                        + std::string(".")
                    );
                }
            }
        }
    }

    //Constructor
    L_DirectoryReader(const L_PathData& pathData) :
        pathData(pathData),
        dirHandle(),
        currentDirEntry()
    {
        //Obtain file handle
        const char* openDirPathCString = (kSLASH_STR + this->pathData.absolutePath.getFullPath()).c_str();
        errno = 0;
        this->dirHandle = opendir(openDirPathCString);

        //Check file handle validity
        if(this->dirHandle == nullptr)
        {
            int errorCode = errno;

            switch(errorCode)
            {
                case EACCES:
                {
                    throw os3util::fileh::exc::FileIOException(std::string("Could not find directory:") + kNEWLINE_STR + this->pathData.relativePath.getFullPath() + kNEWLINE_STR + std::string("permission denied."));
                } break;
                case ENOENT:
                {
                    throw os3util::fileh::exc::FileIOException(std::string("Could not find directory:") + kNEWLINE_STR + this->pathData.relativePath.getFullPath() + kNEWLINE_STR + std::string("does not exist."));
                } break;
                case ENOTDIR:
                {
                    throw os3util::fileh::exc::FileIOException(std::string("Could not find directory:") + kNEWLINE_STR + this->pathData.relativePath.getFullPath() + kNEWLINE_STR + std::string("is not a directory."));
                } break;
                default:
                {
                    throw os3util::fileh::exc::FileIOException(std::string("Could not find directory:") + kNEWLINE_STR + this->pathData.relativePath.getFullPath() + kNEWLINE_STR + std::string("error code ") + os3util::strfunc::intToString(errorCode) + std::string(" received."));
                }
            }
        }
        else
        {
            try
            {
                this->readDir();
            }
            catch(...)
            {
                closedir(this->dirHandle);
                throw;
            }
        }
    }

    //Destructor
    ~L_DirectoryReader()
    {
        try
        {
            errno = 0;
            closedir(this->dirHandle);
            if(errno != 0)
            {
                int errorcode = errno;
                std::cout << "failed to close dirhandle for directory \"" << this->pathData.relativePath.getFullPath() << "\" with error code " << errorcode << std::endl;
            }
        }
        catch(...)
        {
            try
            {
                std::cout << "exception occured while closing dir handle" << std::endl;
            }
            catch(...)
            {
                /*Swallow, destructors should never throw*/
            }
        }
    }

};

问题是,我一直得到ENOENT的例外。但不总是。我(手动)一遍又一遍地为同一目录调用它,有时它按预期打印所有内容(和子目录内容),有时会抛出异常。有时第一次呼叫成功,有时第一次呼叫失败。我根本没有对目录做任何事情,他们只是呆在同一个地方,没有动过。

我发现类似问题的其他主题没有将errno设置为0,但正如上面的代码所示,我正在这样做。我甚至在将const char *设置为0之前构建errno参数,以防万一。

结构体在函数内部构造。如果抛出任何异常,析构函数将激活并关闭DIR句柄。调试确认了这一点。析构函数中的错误消息永远不会发生。唯一可能出错的是dirHandle为空,并且构造函数在该场景中失败。

当我禁用递归时,它总是适用于根目录,但它经常对任何根目录的子目录失败。根目录是home/myname/os3/serverfiles。我的项目位于一个完全不同的目录中,所以我总是通过绝对路径访问它。

每次访问此结构时,都是通过完全相同的函数调用。我的程序中没有任何随机因素。

我对可能导致这种情况的想法缺乏了解。我特别困惑的是,当文件明显存在并且经常找到它们时,错误是ENOENT

1 个答案:

答案 0 :(得分:5)

const char* openDirPathCString = (kSLASH_STR + this->pathData.absolutePath.getFullPath()).c_str();

您正在语句末尾销毁的临时字符串上调用string::c_str(),从而产生悬空指针。

相关问题