将 dirent->d_name 与字符串一起使用失败

Using dirent->d_name together with string fails

本文关键字:字符串 一起 失败 name dirent- gt      更新时间:2023-10-16


我正在编写一个使用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

pathstring的类型,条目是dirent *的类型。
这样,该程序会导致内存访问错误,而没有。
我发现错误是由

引起的
(path + entry->d_name)

,但这不是语句中的隐式转换为string,因为其他测试(例如cout << entry->d_name;path += entry->d_name)也以相同的错误失败。因此,很明显,将entry->d_name用作char *的失败,尽管它是这样定义的(在dirent.h的文档中)。
为什么发生这种故障?

编辑
在程序的稍后,我将entry->d_name添加到vector<string>,这不会引起任何问题。

失败在检查是否等于nullptr之前访问条目。
因为如果条目等于nullptr,则停止我的循环发作,所以最后一次迭代会导致错误。