【问题标题】:How to convert a boost::filesystem::directory_iterator to a const char *如何将 boost::filesystem::directory_iterator 转换为 const char *
【发布时间】:2013-04-25 10:24:44
【问题描述】:

我想遍历目录中的所有文件并打印它们的内容。 Boost 很好地处理了迭代部分,但我不知道如何将其转换为 const char *

boost::filesystem::directory_iterator path_it(path);
    boost::filesystem::directory_iterator end_it;
    while(path_it != end_it){
      std::cout << *path_it << std::endl;

      // Convert this to a c_string
      std::ifstream infile(*path_it);
    }

我尝试阅读此documentation,但找不到类似stringc_str() 的内容。我是C++boost 的新手,希望能找到一些javadoc 之类的文档,这些文档基本上可以告诉我成员是什么以及可用的功能,而不是转储源代码。

抱歉,有人能告诉我如何将*path_it 转换为c string

【问题讨论】:

  • 它在directory_entry
  • 谢谢,从这里弄明白了。关于如何以不那么痛苦的方式学习 boost 的任何提示?
  • 我认为最好的办法是尝试找到单元测试。或者自己写出来弄清楚。

标签: c++ boost boost-filesystem


【解决方案1】:

当您取消引用迭代器时,它会返回 directory_entry:

const directory_entry& entry = *path_it;

您可以将它与operator&lt;&lt;ostream 一起使用,正如您所发现的:

std::cout << entry << std::endl;

您可以使用ostringstream 创建一个字符串:

std::ostringstream oss;

oss << entry;

std::string path = oss.str();

或者,您可以直接从directory_entrystring 的形式访问路径:

std::string path = entry.path().string();

【讨论】:

  • 感谢您的评论和回答。
【解决方案2】:

查看文档后,我认为您可以执行 path_it-&gt;path().c_str(),因为 directory_iterator 会迭代 directory_entry,而 directory_entry 具有 path() 函数,而 c_str() 函数又具有 c_str() 函数。

【讨论】:

  • 我需要做path_it-&gt;path().string().c_str() 才能让它工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-25
  • 1970-01-01
  • 2015-04-02
  • 1970-01-01
相关资源
最近更新 更多