Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.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++ 目录遍历应用程序(readdir\r和stat)在异常时以静默方式失败_C++_Exception Handling_Readdir - Fatal编程技术网

C++ 目录遍历应用程序(readdir\r和stat)在异常时以静默方式失败

C++ 目录遍历应用程序(readdir\r和stat)在异常时以静默方式失败,c++,exception-handling,readdir,C++,Exception Handling,Readdir,我已经使用“readdir\u r”实现了遍历目录层次结构,当我向函数传递以“/”符号结尾的字符串时,它会按预期工作,例如:“../../../” 但是当我传递“/”之类的消息时,程序会无声地失败,尽管它应该抛出IOFileAccessException类型的异常。它发生在这里(调用stat失败后) IOFileAccessException::IOFileAccessException( 常量std::字符串和文件名, const std::字符串和操作, int错误代码) :运行时错误(“访

我已经使用“readdir\u r”实现了遍历目录层次结构,当我向函数传递以“/”符号结尾的字符串时,它会按预期工作,例如:“../../../”

但是当我传递“/”之类的消息时,程序会无声地失败,尽管它应该抛出IOFileAccessException类型的异常。它发生在这里(调用stat失败后)

IOFileAccessException::IOFileAccessException(
常量std::字符串和文件名,
const std::字符串和操作,
int错误代码)
:运行时错误(“访问文件时出错\'”+文件名+
“\”。失败的操作:\”+操作+“\”。错误消息:“+strerror(errcode)){
}
...
//准备方向结构
long int name_max=pathconf(dir.c_str(),_PC_name_max);
如果(name_max==-1)/*未定义限制,或错误*/
名称_max=255;/*猜猜看*/
long int len=偏移量(结构方向,d_名称)+名称_最大值+1;
struct dirent*thedir=static_cast(malloc(len));
而(!dirs.empty()){
...
DIR*d=opendir(currentdir.c_str());
...
struct dirent*result=NULL;
做{
int res=readdir\u r(d、thedir和result);
如果(res>0){//错误处理并抛出异常。在我们的例子中它不会抛出}
结构统计buf;
res=stat(d_name.c_str(),&buf);
如果(res==-1){
int err=errno;
抛出IOFileAccessException(d_name,“stat(目录为\'”+currentdir+“\”),err);
}
}while(结果!=NULL);
...
在单步执行代码时,我发现在调用“:runtime_error(…”)之后,它在异常构造函数中失败

另一件奇怪的事情是,对于输入(起始目录)“./…”来说,d_name变量的值为“/。/throw declaration”,而result->d_name的值为“throw declaration”。 结果指针指向与DIR指针相同的地址

看起来像个谜,希望你能帮我解开

我已将孔代码粘贴到pastbin。 没那么大,我只是觉得这样信息会更清晰

如果需要,您甚至可以使用在线编译器编译和测试它

非常感谢您对本案例的任何建议。谢谢。

在您的代码中

string d_name = currentdir + result->d_name;
当您将
“/。”
传递给程序时,
d_name
类似于
“/.xxx”
,因此
stat
失败

您应该确保
currentdir
以斜杠结尾,您可以使用

if (!currentdir.empty() && 
    *currentdir.rbegin() != '/')
{
    currentdir += '/';
}
if (!currentdir.empty() && 
    *currentdir.rbegin() != '/')
{
    currentdir += '/';
}