我实现了这个简单的函数以递归清空文件夹(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 并避免缓存它们的地方直接使用 c_str()
(如选项 2)。
关于c++ - 递归 std::stringstream 和 c_str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24011182/