c++开发
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <regex>
#include <algorithm>
struct IPCounter {
std::string ip;
int count;
};
// 函数:处理日志文件,统计 IP 地址出现次数
void processLogFile(const std::string& logFilePath, std::vector<IPCounter>& ipCounters) {
std::ifstream inputFile(logFilePath);
std::string line;
if (!inputFile.is_open()) {
std::cerr << "无法打开文件: " << logFilePath << std::endl;
exit(EXIT_FAILURE);
}
std::regex ipRegex(R"(\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b)");
while (std::getline(inputFile, line)) {
std::smatch match;
if (std::regex_search(line, match, ipRegex)) {
std::string ip = match[0];
auto it = std::find_if(ipCounters.begin(), ipCounters.end(),
[&](const IPCounter& counter) { return counter.ip == ip; });
if (it != ipCounters.end()) {
it->count++;
} else {
ipCounters.push_back({ip, 1});
}
}
}
}
// 函数:将 IP 地址统计结果按访问次数排序,并写入文件
void writeSortedIPCountsToFile(const std::vector<IPCounter>& ipCounters, const std::string& outputFilePath) {
std::vector<IPCounter> sortedCounters = ipCounters;
// 按访问次数从大到小排序
std::sort(sortedCounters.begin(), sortedCounters.end(),
[](const IPCounter& a, const IPCounter& b) { return a.count > b.count; });
std::ofstream outputFile(outputFilePath);
if (!outputFile.is_open()) {
std::cerr << "无法打开写入文件: " << outputFilePath << std::endl;
exit(EXIT_FAILURE);
}
for (const auto& counter : sortedCounters) {
outputFile << "IP: " << counter.ip << ", 访问次数: " << counter.count << '\n';
}
}
// 主程序
int main() {
std::string logFilePath;
std::cout << "请输入日志文件路径: ";
std::getline(std::cin, logFilePath);
std::string outputFilePath = "log_analysis_result.txt"; // 替换为你的输出文件路径
std::vector<IPCounter> ipCounters;
// 处理日志文件
processLogFile(logFilePath, ipCounters);
// 将结果按访问次数排序并写入文件
writeSortedIPCountsToFile(ipCounters, outputFilePath);
std::cout << "IP访问次数已按大小排序并写入 " << outputFilePath << std::endl;
return 0;
}
处理效果还是比较客观