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 directory\n";
}
else
cout << p << " does not exist\n";
}
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
此外,当我将鼠标移到路径()上时,它会显示:class boost::filesystem3::path Error: typename not allowed
答案 0 :(得分:2)
此部分(for
的正文)存在问题:
path fn = it->path().filename(); // extract the filename from the path
v.push_back(fn); // push into vector for later sorting
it
指向path
个对象,因此我不明白为什么调用path()
。似乎应该用it->filename()
编辑:看一下原始示例,我看到这些是您的修改。如果要存储文件名而不是打印它们,请定义另一个string
或path
向量并在其中存储文件名,不要重复使用第一个。{1}}或path()
。删除对std::transform
的调用应解决编译问题。
编辑2 :作为一个可爱的BTW,您可以使用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));
仿函数:
{{1}}
答案 1 :(得分:0)
发布链接后,似乎发布的代码工作正常。但问题是在for
循环中的修改代码中引入的。第一个问题是,path()
是一个构造函数。第二个问题,我不确定boost::path是否包含任何方法filename()
。你可以试试,
path fn = (*it);