[C++] 纯文本查看 复制代码 #include <iostream>
#include <filesystem>
#include <vector>
#include <string>
#include <regex>
#include <fstream>
#include <iomanip>
#include <algorithm>
namespace fs = std::filesystem;
// 自定义结构体
struct DriveLog {
std::string date;
std::string file1;
std::string file2;
std::uintmax_t size1;
std::uintmax_t size2;
bool complete;
std::string remark;
// 输出格式
friend std::ostream& operator<<(std::ostream& os, const DriveLog& log) {
os << std::left << std::setw(10) << log.date
<< std::setw(50) << (log.file1 + "|" + log.file2)
<< std::setw(10) << (std::to_string(log.size1) + "|" + std::to_string(log.size2))
<< std::setw(10) << (log.complete ? "真" : "假")
<< log.remark;
return os;
}
};
// 获取文件大小
std::uintmax_t getFileSize(const std::string& path) {
return fs::exists(path) ? fs::file_size(path) : 0;
}
// 解析文件并填充 DriveLog
std::vector<DriveLog> parseLogs(const std::string& directory) {
std::vector<DriveLog> logs;
std::regex logPattern(R"(drive-(\d{6})-HD1-(\d)\.log)");
std::map<std::string, DriveLog> logMap;
for (const auto& entry : fs::directory_iterator(directory)) {
if (entry.is_regular_file()) {
std::string filename = entry.path().filename().string();
std::smatch match;
if (std::regex_match(filename, match, logPattern)) {
std::string date = match[1];
int fileType = std::stoi(match[2]);
if (logMap.find(date) == logMap.end()) {
logMap[date] = {date, "", "", 0, 0, true, ""};
}
if (fileType == 1) {
logMap[date].file1 = filename;
logMap[date].size1 = getFileSize(entry.path().string());
} else if (fileType == 2) {
logMap[date].file2 = filename;
logMap[date].size2 = getFileSize(entry.path().string());
}
}
}
}
// 检查完整性并生成备注
for (auto& [date, log] : logMap) {
if (log.file1.empty()) {
log.complete = false;
log.remark = "缺少drive-" + date + "-HD1-1.log文件";
}
if (log.file2.empty()) {
log.complete = false;
log.remark += (log.remark.empty() ? "" : " | ") + "缺少drive-" + date + "-HD1-2.log文件";
}
logs.push_back(log);
}
// 按日期排序
std::sort(logs.begin(), logs.end(), [](const DriveLog& a, const DriveLog& b) {
return a.date > b.date;
});
return logs;
}
int main() {
std::string directory = "aaa"; // 你的目录
std::vector<DriveLog> logs = parseLogs(directory);
// 输出表头
std::cout << std::left << std::setw(5) << "序号"
<< std::setw(10) << "日期"
<< std::setw(50) << "相关文件名"
<< std::setw(10) << "相关文件大小"
<< std::setw(10) << "是否完整"
<< "备注" << std::endl;
// 输出每一行
int index = 1;
for (const auto& log : logs) {
std::cout << std::setw(5) << index++ << log << std::endl;
}
return 0;
}
|