将 dirent->d_name 与字符串一起使用失败
Using dirent->d_name together with string fails
我正在编写一个使用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
用作char *
的失败,尽管它是这样定义的(在dirent.h的文档中)。
为什么发生这种故障?
编辑:
在程序的稍后,我将entry->d_name
添加到vector<string>
,这不会引起任何问题。
失败在检查是否等于nullptr
之前访问条目。
因为如果条目等于nullptr
,则停止我的循环发作,所以最后一次迭代会导致错误。
相关文章:
- 有没有办法在C++将字符串与开关语句一起使用?
- 我如何将 OR 与 if 语句一起使用字符串
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 将 NULL 与 C 的字符* 字符串一起使用
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- 编译器如何将链表中的地址字符串在一起?
- 将find_last_of与字符串C++一起使用
- 在 c++ 中将 find_first_of 与字符串一起使用,而不是一组预定义字符
- 如何将adjacent_find与字符串C++一起使用
- 可以将std::getline()与从std::string中移出的字符串一起使用吗
- 如何在不使用模板的情况下将variadic函数与字符串一起使用
- 将 dirent->d_name 与字符串一起使用失败
- 如何将开关与字符串一起使用
- 将两个字符串一起分配,获取访问读取冲突
- C++ - 将 sendto() 与基本字符串一起使用
- 如何在C++中将 atoi 函数与字符串一起使用
- 将 <null> printf 与字符串一起使用
- 除非我通过data()或C_str()运行cout,否则无法将它与C++字符串一起使用
- C++-将.at()方法与字符串一起使用时出现问题
- 如何将replace_if与字符串一起使用