配置文件模板:
# Raw
raw:
{
fS = 48000;
hopSize = 960;
nBits = 16;
nChannels = 6;
type = "callback";
}
本次的解析代码,可以通过关键模块key找到该模块下的第一个字符并返回=后面的字符串。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct data
{
int nChannels;
int fS;
int nBits;
char * type;
FILE * fp;
}DATA_T;
char * cfg = "audio.cfg";
char *get_string_by_key(char *title, char *key, FILE * fp)
{
int flag = 0;
char *wTmp;
static char sLine[MAX];
rewind(fp); /*从开头开始*/
while (NULL != fgets(sLine, MAX, fp))
{
if (0 == strncmp("//", sLine, 2)) continue;
if ('#' == sLine[0]) continue;
wTmp = strchr(sLine, '=');
if ((NULL != wTmp) && (1 == flag))
{
if(strstr(sLine, key) != NULL){
return wTmp+1;
}
}
else if (flag == 0)
{
if (0 == strncmp(title, sLine, strlen(title)))
{
flag = 1; /*找到key模块*/
}
}
}
return "";
}
int get_int_from_cfg(char *title, char *key, FILE * fp)
{
return atoi(get_string_by_key(title, key, fp));
}
char * get_string_from(char *title, char *key, FILE * fp)
{
char * str = get_string_by_key(title, key, fp);
char *str2 = str;
int i=0;
while (*str2)
{
if (*str2 != ';' && *str2 != '"' && *str2 != '\n' && *str2 != ' ')
str[i++] = *str2;
str2++;
}
str[i]=0; //消除回车
return str;
}
int main(int argc, char * argv[])
{
if (argc == 2)
{
cfg = argv[1];
}
DATA_T audio;
if((audio.fp = fopen(cfg, "r")) == NULL)
{
perror("fopen()");
return -1;
}
audio.nChannels = get_int_from_cfg("raw:", "nChannels", audio.fp);
audio.fS = get_int_from_cfg("raw:", "fS", audio.fp);
audio.nBits = get_int_from_cfg("raw:", "nBits", audio.fp);
audio.type = get_string_from("raw:", "type", audio.fp);
printf("nChannels = %d\n", audio.nChannels);
printf("fS = %d\n", audio.fS);
printf("nBits = %d\n", audio.nBits);
printf("type =%s\n", audio.type);
fclose(audio.fp);
return 0;
}
执行结果