我正在编写一个使用该dirent.h
库的 C++ 应用程序,以从目录中读取文件。有一次我想在文件和目录之间做出决定。为此,我添加了以下代码:
entry = readdir(used_directory); //read next object from directory stream
DIR* directory_test = opendir((path + entry->d_name).c_str()); //try to open object as directory
if ( directory_test != nullptr) { //object is directory
if (entry != nullptr) { //reading from directory succeeded
dirs.push_back(entry->d_name); //add filename to file list
++dircounter;
}
}
else { //object is file
path
是类型,string
条目是类型dirent *
。
有了这个,程序会导致内存访问错误,没有它不会。
我想通了,该错误是由
(path + entry->d_name)
但这不是string
语句中的隐式转换,因为其他测试也喜欢cout << entry->d_name;
或path += entry->d_name
失败并出现相同的错误。所以显然使用entry->d_name
as是失败的char *
,尽管它是这样定义的(在 dirent.h 的文档中)。
为什么会发生这种故障?
编辑:
稍后在我添加entry->d_name
到 a的程序中vector<string>
,这不会导致任何问题。