提升文件系统版本 3 问题

boost filesystem version 3 issue?

本文关键字:问题 版本 文件系统      更新时间:2023-10-16

boost网站上的示例代码不起作用。 http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/tutorial.html#Using-path-decomposition

int main(int argc, char* argv[])
{
  path p (argv[1]);   // p reads clearer than argv[1] in the following code
  try
  {
    if (exists(p))    // does p actually exist?
    {
      if (is_regular_file(p))        // is p a regular file?   
        cout << p << " size is " << file_size(p) << 'n';
      else if (is_directory(p))      // is p a directory?
      {
        cout << p << " is a directory containing:n";
        typedef vector<path> vec;             // store paths,
        vec v;                                // so we can sort them later
        copy(directory_iterator(p), directory_iterator(), back_inserter(v));
        sort(v.begin(), v.end());             // sort, since directory iteration
                                          // is not ordered on some file systems
        for (vec::const_iterator it (v.begin()); it != v.end(); ++it)
        {
          path fn = it->path().filename();   // extract the filename from the path
          v.push_back(fn);                   // push into vector for later sorting
        }
      }
      else
        cout << p << " exists, but is neither a regular file nor a directoryn";
    }
    else
      cout << p << " does not existn";
  }
  catch (const filesystem_error& ex)
  {
    cout << ex.what() << 'n';
  }
  return 0;
} 

在 Visual Studio 2010 中为该行编译时出现两条错误消息path fn = it->path().filename();

第一个错误是:'function-style cast' : illegal as right side of '->' operator,第二个错误是:left of '.filename' must have class/struct/union

另外,当我将鼠标悬停在 path() 上时,它说:class boost::filesystem3::path Error: typename not allowed

本节(for的正文)有问题:

  path fn = it->path().filename();   // extract the filename from the path
  v.push_back(fn);                   // push into vector for later sorting
  1. it指向path对象,所以我不明白为什么调用path()。似乎应该用it->filename()代替
  2. 您将文件名推送到同一向量的末尾,因此在循环之后,您将拥有两次包含文件列表的向量,首先是路径名,然后是文件名。

编辑:查看原始示例,我发现这些是您的修改。如果要存储文件名而不是打印文件名,请定义另一个stringpath向量并将文件名存储在其中,不要重复使用第一个。 删除对path()的调用应该可以解决编译问题。

编辑2:作为一个可爱的BTW,您可以使用std::transform而不是std::copy一次性实现目录遍历和文件名提取:

struct fnameExtractor {  // functor
  string operator() (path& p) { return p.filename().string(); }
};
vector<string> vs;
vector<path> vp;
transform(directory_iterator(p), directory_iterator(), back_inserter(vs),
          fnameExtractor());

使用mem_fun_ref而不是fnameExtractor函子相同:

transform(directory_iterator(p), directory_iterator(), back_inserter(vp),
          mem_fun_ref(&path::filename));

发布链接后,发布的代码似乎工作正常。但是问题for循环中修改后的代码中引入了问题。第一个问题是,path()是一个构造函数。第二个问题,我不确定 boost::p ath 包含任何方法作为filename()。你可以试试,

path fn = (*it);