1. 枚举文件
这里先给 boost::filesystem 取个别名,后面代码会顺手很多。流程很直白:把 src_path 转成 root_path,先判断目录是否存在,不存在就直接返回;存在的话,就递归遍历里面的文件。
遍历时只保留普通文件,并且扩展名必须是 .html。符合条件的路径再转成 string,放进 file_list。这个地方别把 .string() 换成 to_string(),前者是路径对象自己的接口,后者不是拿来处理路径的。
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 读取并拆字段
ParseHtml 负责把文件串起来处理:先读内容,再提取标题、正文和 URL。中间任一步失败,就跳过这份文件,不把脏数据往后传。
bool ParseHtml(const std::vector<std::string> &files_list, std::string &src_path, std::vector<DocInfo_t> *results) {
( std::string &file : files_list) {
std::string tr;
(!ns_util::FileUtil::(file, &tr)) ;
DocInfo doc;
(!(tr, &doc.title)) ;
(!(tr, &doc.content)) ;
(!(file, src_path, &doc.url)) ;
results->(doc);
}
;
}


