日志处理小工具

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;
}

处理效果还是比较客观

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值