为什么 opendir() 在使用 c_str() 转换路径类型后不打开路径?
Why won't opendir() open a path after converting the path type with c_str()?
我试图打开一个目录,其中的名称(路径)目前是在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());
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 为自定义路径类型设置提升property_tree
- 查找树(不属于任何特定类型的简单连接树)中两个节点之间的路径
- 创建进程使用路径时出现错误事件:类型 "char *" 的 E0167 参数与类型 "LPWSTR" 的参数不兼容
- 说明 资源路径位置类型 'UINT16_MAX' 未在此范围内声明
- 类型名称路径由一个静态变量隐藏
- 为什么对于具有多个返回路径的lambda返回lambda,我会得到一个类型推导错误
- 为什么 opendir() 在使用 c_str() 转换路径类型后不打开路径?
- Windows中的绝对路径类型
- 当构造函数具有相同的参数类型(文件路径)时,如何从数组创建(初始化)std::元组
- 在c++中有没有办法允许不同的数据类型有不同的执行路径?