为什么 opendir() 在使用 c_str() 转换路径类型后不打开路径?

Why won't opendir() open a path after converting the path type with c_str()?

本文关键字:路径 类型 转换 opendir 为什么 str      更新时间:2023-10-16

我试图打开一个目录,其中的名称(路径)目前是在std::字符串最初从一个。csv文件读取(虽然我不认为改变任何关于字符串本身)。调用opendir(path.c_str())返回NULL。我尝试了以下代码,在opendir()之外进行转换:

DIR *dir;
bool first = True;
string level = "";
struct dirent *ent;
const char * c = path.c_str();
// A
if ((dir = opendir(c)) != NULL){
    // do stuff
    // should open the directory and go here
}else{
    // always ends up here
}

当path="LeanDataBase"失败时,项目文件夹中的目录,用opendir("LeanDataBase")代替opendir(c)似乎打开了目录。然而,这个函数是递归的,所以我不能硬编码这个值,否则它不会工作并陷入无限循环。

我还尝试打印类型,在前面的代码中"A"后面插入以下两行:

cout << typeid(c).name() << endl;
cout << typeid("LeanDataBase").name() << endl;

产生如下输出:

PKc
A13_c

这是否意味着我传递了错误的类型给opendir()?它似乎可以处理PKc,但不能处理A13_c。是否有方法将路径字符串转换为正确的类型?

查看我的水晶球,我看到以下问题:在path.c_str()被调用之后,但在opendir()被调用之前,路径被修改(甚至离开作用域)。在任何变量中记住c_str()的结果通常是一个不好的做法,因为它会导致这样的问题。c_str()用于就地使用,如以下

opendir(path.c_str());