我正在尝试打开一个目录,该目录的名称 (path) 当前位于最初从 .csv 文件读取的 std::string 中(尽管我不认为更改字符串本身的任何内容)。调用 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。有没有办法将路径字符串转换为正确的类型?
最佳答案
看看我的 Crystal 球,我看到以下问题:路径在 path.c_str()
之后被修改(甚至离开范围)被调用,但在 opendir()
之前叫做。记住 c_str()
的结果通常是一种不好的做法在任何变量中,因为它会导致这样的问题。 c_str()
旨在就地使用,例如以下
opendir(path.c_str());
关于c++ - 为什么用c_str()转换路径类型后opendir()不打开路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32875523/