recursive std::stringstream and c_str
recursive std::stringstream and c_str
我已经实现了这个简单的函数,以便递归清空文件夹(Xcode 5.1)。目标平台iOS)。对于传递新目录路径的每个子目录,该函数都会调用自己。
但是在第一次递归调用时,path
参数在再次调用opendir
后归零。path
参数现在是一个空字符串,我不知道为什么。stringstream buf
变量没有被破坏,AFAIK也没有被opendir
改变。
提前感谢您的帮助。
void emptyFolder(const char *path)
{
if (DIR *folder = opendir(path)) {
while (struct dirent *entry = readdir(folder)) {
if (strcmp(entry->d_name,".") == 0 ||
strcmp(entry->d_name,"..") == 0)
continue;
std::stringstream buf;
buf << path << '/' << entry->d_name;
const char *filepath = buf.str().c_str();
if (entry->d_type == DT_DIR)
emptyFolder(filepath);
remove(filepath)
}
closedir(folder);
}
}
正如n.m所说,您需要复制buf.str()的内容,否则您可以将引用直接传递给函数:
选项1:
std::string filepath(buf.str());
if (entry->d_type == DT_DIR)
emptyFolder(filepath.c_str());
remove(filepath.c_str())
选项2:
if (entry->d_type == DT_DIR)
emptyFolder(buf.str().c_str());
remove(buf.str().c_str())
我还建议您使用std::string
而不是const char*
的引用。当您需要使用不支持字符串对象的API并避免缓存它们(如选项2)时,直接使用c_str()
。
相关文章:
- Python str to C++ to Python str
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 字符串变量,比如说"字符串str",可以直接复制到数组中吗?
- 解释一下 for (char c : str) 的作用?
- 调用"stringstream::str()"来获取打印的内容实际上是合法的吗?
- Stringstream STR函数有什么问题
- 初始化 stringstream.str( a_value ) 和 stringstream << a_value 之间的区别
- StringStream的Str方法将不起作用.(不同类型的串联)(C )
- std::stringstream and the str method
- 我是否负责释放/删除stringstream.str()返回的字符串
- Compiler Optimization with return (std::stringstream ss).str
- std::stringstream.str() 输出垃圾
- std::stringstream "str"什么都不返回?
- Std::stringstream.str()总是返回同一个字符串
- 为什么stringstream::str()截断string
- GDB调试libstdc++找不到stringstream str()方法
- c++中stringstream::str()的正确使用
- 用str(const char*)设置std::stringstream的内容会产生奇怪的后果