在一个跨平台( Android 、Windows、Linux )项目中配置文件用 INI 格式,自己写了个解析库,纯C语言的,简单好用。
可以解析 INI 格式的字符串、解析文件、保存到文件。
下面是头文件:
#ifndef INI_PARSER_H
#define INI_PARSER_H
#ifdef __cplusplus
extern "C" {
#endif
struct tag_value_list;
struct ini_parser {
struct tag_value_list * keyvalues;
int (*parse_file)(struct ini_parser *, const char * file);
int (*parse_string)(struct ini_parser *, const char *text);
char * (*value)(struct ini_parser *, const char * key);
void (*set_value)(struct ini_parser *, const char * key, const char * value);
void (*remove)(struct ini_parser *, const char *key);
int (*save_to_file)(struct ini_parser *, const char * file);
};
struct ini_parser * new_ini_parser();
void delete_ini_parser(struct ini_parser *);
#ifdef __cplusplus
}
#endif
#endif // INI_PARSER_H
下面是源文件:
#include "ini_parser.h"
#include <stdio.h>
#include <string.h>
#include "tag_value.h"
static struct tag_value_pair * parse_line(char *line, int len)
{
struct tag_value_pair * pair = 0;
int count = 0;
char * p = line;
char * end = 0;
char * start = line;
if(!p) return 0;
while(*p == ' ') p++;
/*blank line*/
if(p - line == len ||
*p == '\r' ||
*p == '\n' ||
*p == '\0') return 0;
/*do not support group*/
if(*p == '[') return 0;
/*comments*/
if(*p == '#') return 0;
/* extract key *