c++ - 递归 std::stringstream 和 c_str

标签 c++ std

我实现了这个简单的函数以递归清空文件夹(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/

相关文章:

C++ 模板和比较不同类型

c++ - 构造函数不设置成员变量

c++ - 信号处理程序中不允许使用对象或函数

C++11 没有匹配函数来调用‘std::vector

c++ - Boost::convex_hull 分散的二维点在 STL 容器中

c# - 如何在 C# 中使用 UrlMon.dll 中的 CreateUri 方法

c++ - g++ 找到 -lXext 但 MinGW 找不到它,错误为 : i586-mingw32msvc/bin/ld: cannot find -lXext

c++ - 使用 std::thread 从 C++11 中的两个类调用函数

c++ - std::make_unique 可以与抽象接口(interface)一起使用吗?

c++ - std::regex,匹配字符串的开始/结束