czdb ip查询main.c代码

#include "db_searcher.h"
#include <string.h>
#include <unistd.h>
#include <time.h>

int main(int argc, char *argv[]) {
    char* dbPath = NULL;
    char* key = NULL;
    char* searchMode = NULL;
    int opt;

    while ((opt = getopt(argc, argv, "p:k:m:")) != -1) {
        switch (opt) {
        case 'p':
            dbPath = optarg;
            break;
        case 'k':
            key = optarg;
            break;
        case 'm':
            searchMode = optarg;
            break;
        default:
            fprintf(stderr, "Usage: %s -p dbPath -k key -m searchMode\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    if (dbPath == NULL || key == NULL || searchMode == NULL) {
        fprintf(stderr, "Both -p, -k and -m options are required.\n");
        fprintf(stderr, "Usage: %s -p dbPath -k key -m searchMode\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int mode;
    if (strcmp(searchMode, "memory") == 0) {
        mode = MEMORY;
    } else if (strcmp(searchMode, "btree") == 0) {
        mode = BTREE;
    } else {
        fprintf(stderr, "Invalid search mode. It should be either 'memory' or 'btree'.\n");
        exit(EXIT_FAILURE);
    }

    DBSearcher* dbSearcher = initDBSearcher(dbPath, key, mode);

    info(dbSearcher);

    FILE *inputFile = fopen("2.txt", "r");  
    if (inputFile == NULL) {  
        perror("Error opening input file");  
        exit(EXIT_FAILURE);  
    }  
  
    FILE *outputFile = fopen("3.txt", "w");  
    if (outputFile == NULL) {  
        perror("Error opening output file");  
        fclose(inputFile); // 不要忘记关闭已经打开的文件  
        exit(EXIT_FAILURE);  
    }  
  
    char ip[50];  
    char region[100];  
  
    // 从2.txt中读取每行并处理  
    while (fgets(ip, sizeof(ip), inputFile)) {  
        // 移除字符串末尾的换行符(如果有的话)  
        ip[strcspn(ip, "\n")] = 0;  
  
        // 搜索IP地址  
        if (search(ip, dbSearcher, region, sizeof(region)) == 0) {  
            // 如果搜索成功,将结果写入3.txt  
            fprintf(outputFile, "IP: %s, Region: %s\n", ip, region);  
        } else {  
            // 如果搜索失败或发生错误,写入一条错误消息  
            fprintf(outputFile, "IP: %s, Result: Not found or error occurred\n", ip);  
        }  
    }  
  
    // 关闭文件  
    fclose(inputFile);  
    fclose(outputFile);  
    
    closeDBSearcher(dbSearcher);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值