1. 文件枚举
我们要使用到 boost 里面 filesystem 这个命名空间里面的函数,所以我在这里先给它取个别名。然后我们把 src_path 里面的路径交给 root_path。接着我们判断这个路径是否存在,如果不存在那就直接结束代码。接着我们通过迭代器循环的方式来对 root_path 里面的每一个文件。
第一个 if 用来判断是否是普通文件,第二个 if 来判断文件的扩展名是否为 .html,接着走到最后就书面是扩展名为 .html 的普通文件。然后我们就把它的路径转化为 string 类型。
注意:在这里不可以把 .string() 换成 to_string()。这是因为:
.string()是std::filesystem::path类的成员函数,专门用于将路径对象转换为std::string类型的字符串(返回路径的字符串表示)。to_string()是 C++ 标准库中的全局函数(或针对基础类型的重载),用于将数值类型(如int、double等)转换为字符串,不能直接用于路径对象。
bool EnumFile(const std::string &src_path, std::vector<std::string> *file_list) {
namespace fs = boost::filesystem;
fs::path root_path(src_path);
if (!fs::exists(root_path)) {
std::cout << src_path << " is not exist" << std::endl;
return false;
}
fs::recursive_directory_iterator end;
for (fs::recursive_directory_iterator iter(root_path); iter != end; iter++) {
if (!fs::is_regular_file(*iter)) continue;
if (iter->path().extension() != ".html") continue;
file_list->push_back(iter->path().string());
}
return true;
}
2. 内容解析
2.1 读取并解析(去标签化)
这个就是去标签化的函数,通过一步步对文件的解析分别提出 title 和 content,然后构建出 url,接下来就是把 doc 里面的内容交给 results。


