recursive std::stringstream and c_str

recursive std::stringstream and c_str

本文关键字:str stringstream std recursive and      更新时间:2023-10-16

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