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
此外,当我将鼠标放在path()上时,它会显示:class boost::filesystem3::path Error: typename not allowed
发布于 2011-05-17 13:48:23
这个部分(for的主体)是有问题的:
path fn = it->path().filename(); // extract the filename from the path
v.push_back(fn); // push into vector for later sortingit指向path对象,所以我不明白为什么要调用path()。似乎它应该被替换为在相同的向量末尾的it->filename()编辑:查看原始示例,我发现这些是您的修改。如果你想存储文件名而不是打印它们,定义另一个string或path矢量并在其中存储文件名,不要重用第一个矢量。删除对path()的调用应该可以解决编译问题。
EDIT 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));发布于 2011-05-17 12:20:33
在你发布了链接之后,看起来发布的代码运行良好。但在修改后的for循环代码中引入了问题。第一个问题是,path()是一个构造器。第二个问题,我不确定作为filename()的boost::path是否包含任何方法。你可以试一试
path fn = (*it);https://stackoverflow.com/questions/6026114
复制相似问题