基于Getopt读取ini的C实现
由于工作需要,写了一个通过配置文件启动选项的 C接口。用于自己的使用,在这里记录一下。
以下代码在linux ContOS下测试通过。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "ini.h"
#include "tcpcopy.h"
/* 功能:从指定的配置文件中获取相关设置参数 */
/* 编译: gcc -o main main.c ini.c */
/* 测试: ./main F:tcpcopy.ini */
/*功能: 配置文件默认值 */
#define TCPCOPY_CONFIG_INI_FILE "./tcpcopy.ini"
char config_ini_file_name;
xcopy_clt_settings clt_settings;
/*功能: 显示从配置文件读取的配置项 */
void config_clt_setting_display()
{
printf("clt_settings.raw_transfer=%s.\n", clt_settings.raw_transfer);
printf("clt_settings.raw_clt_tf_ip=%s.\n", clt_settings.raw_clt_tf_ip);
printf("clt_settings.replica_num=%d.\n", clt_settings.replica_num);
printf("clt_settings.factor=%d.\n", clt_settings.replica_num);
printf("clt_settings.max_rss=%d.\n", clt_settings.replica_num);
printf("clt_settings.par_connections=%d.\n", clt_settings.replica_num);
printf("clt_settings.log_path=%s.\n", clt_settings.log_path);
printf("clt_settings.mtu=%d.\n", clt_settings.mtu);
printf("clt_settings.mss=%d.\n", clt_settings.mss);
}
/*功能:清理xcopy_clt_settings的内存 */
void clear_clt_setting()
{
free(clt_settings.raw_transfer);
free(clt_settings.raw_clt_tf_ip);
free(clt_settings.log_path);
}
/*功能: ini 文件回调,读取Ini详细信息 */
static int ini_read_handler(void* user, const char* section, const char* name,
const char* value)
{
#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0
if (MATCH("config", "x")) {
clt_settings.raw_transfer = strdup(value);
} else if (MATCH("config", "c")) {
clt_settings.raw_clt_tf_ip = strdup(value);
} else if (MATCH("config", "n")) {
clt_settings.replica_num = atoi(value);
} else if (MATCH("config", "f")) {
clt_settings.factor = atoi(value);
} else if (MATCH("config", "m")) {
clt_settings.max_rss = atoi(value);
} else if (MATCH("config", "C")) {
clt_settings.par_connections = atoi(value);
} else if (MATCH("config", "l")) {
clt_settings.log_path = strdup(value);
} else if (MATCH("config", "M")) {
clt_settings.mtu = atoi(value);
} else if (MATCH("config", "S")) {
clt_settings.mss = atoi(value);
} else {
return 0;/* unknown section/name, error */
}
return 1;
}
/*功能: 从路径获取配置文件名称 */
void read_opt_file_name(int argc, char* argv[])
{
int ch;
config_ini_file_name = '\0';
while ((ch = getopt(argc,argv,"F:"))!=-1)
{
switch(ch)
{
case 'f':
printf("option f:'%s'\n", optarg);
sprintf(config_ini_file_name, "%s", optarg);
break;
default:
printf("other option :%c\n",ch);
}
}
}
int main(int argc, char* argv[])
{
read_opt_file_name(argc, argv);
if(strlen(config_ini_file_name) == 0)
{
/* 没有发现设置配置文件 设置一个默认值 */
sprintf(config_ini_file_name, "%s", TCPCOPY_CONFIG_INI_FILE);
}
/* 读取配置文件 */
if (ini_parse(config_ini_file_name, ini_read_handler, NULL) < 0) {
printf("Can't load (%s)\n", config_ini_file_name);
return 1;
}
config_clt_setting_display();
clear_clt_setting();
return 0;
}
页:
[1]