C++ directory_iterator

C++ directory_iterator

本文关键字:iterator directory C++      更新时间:2023-10-16

我已经有一段时间没有使用c++了,请原谅我向新手提出的问题。

我编写了以下代码来获取目录的内容列表,它工作得很好:
for (directory_iterator end, dir("./");
     dir != end; dir++) {
    std::cout << *dir << std::endl;
}

"*dir"返回什么,一个指针的"字符数组",指针指向"字符串"对象,或指针指向"路径"对象?

我想传递"*dir"(如果它以.cpp结尾)给另一个函数(),该函数将在稍后的时间(异步)对其进行操作。我想我需要做一个"*dir"的拷贝。我写了下面的代码:

path *_path;
for (directory_iterator end, dir("./");
     dir != end; dir++) {
    _path = new path(*dir);
    if (_path->extension() == ".cpp") {
        function1(_path);    // function1() will free _path
    } else
        free(_path);
}

谢谢你,艾哈迈德。

来自boost::directory_iterator:

的文档

end迭代器上操作符*的结果没有定义。对于任何其他迭代器值:const directory_entry&返回.

关于函数调用,我认为最简单的方法是:
using namespace boost::filesystem;
for (directory_iterator end, dir("./"); dir != end; dir++) {
  const boost::filesystem::path &this_path = dir->path();
  if (this_path.extension() == ".cpp") {
    function1(this_path); // Nothing to free
  } 
}

其中function1方法可以声明为:

void function1(const boost::filesystem::path this_path);