#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;
}
czdb ip查询main.c代码
最新推荐文章于 2024-09-29 18:05:43 发布