您必须链接 boost_system 和 boost_filesystem 库。如何执行此操作取决于您的编译器/链接器组合;例如,在我的系统上我必须添加标志-lboost_system-mt -lboost_filesystem-mt
.
一些备注:在 Windows 上,您通常需要wstring
(或其他“宽字符”对象)以增加使用 Unicode 路径的机会。其次,您可以使用以下命令使代码更短find_if
and recursive_directory_iterator
:
#include <algorithm>
#include <iostream>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
bool find_file(const path& dir_path, const path& file_name, path& path_found) {
const recursive_directory_iterator end;
const auto it = find_if(recursive_directory_iterator(dir_path), end,
[&file_name](const directory_entry& e) {
return e.path().filename() == file_name;
});
if (it == end) {
return false;
} else {
path_found = it->path();
return true;
}
}
int main() {
const path myPath = L"/usr/local";
const path myFile = L"filesystem.hpp";
path myFound;
find_file(myPath, myFile, myFound);
wcout << myFound << endl;
}
我的示例使用 C++11 功能auto
and lambda
,出现在 GCC 4.6 中。如果您的编译器缺少这些,您可以轻松地将 lambda 替换为谓词对象,然后auto
通过显式类型说明符:
#include <functional>
class file_name_equal: public unary_function<path, bool> {
public:
explicit file_name_equal(const path& fname): file_name(fname) { }
bool operator()(const directory_entry& entry) const {
return entry.path().filename() == file_name;
}
private:
path file_name;
};
bool find_file_cxx03(const path& dir_path, const path& file_name,
path& path_found) {
const recursive_directory_iterator end;
const recursive_directory_iterator it =
find_if(recursive_directory_iterator(dir_path), end,
file_name_equal(file_name));
if (it == end) {
return false;
} else {
path_found = it->path();
return true;
}
}
另一个不错的变体使用 Boost.Optional 摆脱了返回值引用:
...
#include <boost/optional.hpp>
using namespace std;
using namespace boost;
using namespace boost::filesystem;
optional<path> find_file(const path& dir_path, const path& file_name) {
const recursive_directory_iterator end;
const auto it = find_if(recursive_directory_iterator(dir_path), end,
[&file_name](const directory_entry& e) {
return e.path().filename() == file_name;
});
return it == end ? optional<path>() : it->path();
}
int main() {
const path myPath = L"/usr/local";
const path myFile = L"filesystem.hpp";
wcout << find_file(myPath, myFile).get_value_or("not found") << endl;
}