|
![](static/image/common/ico_lz.png)
楼主 |
发表于 2010-5-14 15:02:36
|
显示全部楼层
源码,也可以在windows下用,不过Win下又读写ini文件的API就用不着这个了,不停的调parseconf_get_next_variable就可以返回所有变量的变量名和变量值(都是字符串格式)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PARSECONF_MAX (1024 * 64)
#define PARSECONF_LINE_MAX (1024 * 4)
/* open a config file and return file pointer */
FILE* parseconf_open_file(const char *path)
{
return fopen(path, "r");
}
/* close config file */
int parseconf_close_file(FILE *fp)
{
return fclose(fp);
}
/* get next variable in config file and move file position to next line */
/* return: value length or -1 for file end or call failed */
int parseconf_get_next_variable(FILE *fp, char *name_buf,
int name_buf_size, int *name_len,
char *value_buf, int value_buf_size)
{
char line[PARSECONF_MAX], subline[PARSECONF_LINE_MAX];
char *pline, *plineend, *psub, *psubend, *pequal;
char *pnameend, *pvalue;
int continue_flag, var_name_len, var_value_len;
/* get next variable */
pline = plineend = line;
while ( fgets(subline, sizeof(subline), fp) != NULL ) {
psub = subline;
psubend = psub + strlen(psub);
/* skip space */
for ( ;
psub < psubend && (' ' == *psub || '\t' == *psub);
psub++ );
/* skip comment */
if ( '#' == *psub )
continue;
/* skip empty line */
if ( psub == psubend )
continue;
/* truncation trailing space and "\r" and "\n" */
for ( ;
psubend > psub
&& (' ' == psubend[-1]
|| '\t' == psubend[-1]
|| '\r' == psubend[-1]
|| '\n' == psubend[-1]);
psubend-- );
*psubend = '\0';
/* skip empty line again */
if ( psub == psubend )
continue;
/* continue line ? */
continue_flag = ('\\' == psubend[-1]);
if ( continue_flag )
*--psubend = '\0';
/* link sub line to line */
memcpy(plineend, psub, psubend - psub);
plineend += psubend - psub;
/* line end */
if ( !continue_flag )
break;
}
/* file end ? */
if ( pline == plineend && feof(fp) )
return -1;
/* terminate line */
*plineend = '\0';
/* find equal */
pequal = strchr(pline, '=');
if ( NULL == pequal )
pequal = plineend;
/* find variable's name */
for ( pnameend = pequal;
pnameend > pline
&& (' ' == pnameend[-1] || '\t' == pnameend[-1]);
pnameend-- );
var_name_len = pnameend - pline;
if ( (var_name_len + 1) > name_buf_size )
return -2;
memcpy(name_buf, pline, var_name_len);
name_buf[var_name_len] = '\0';
if ( NULL != name_len )
*name_len = var_name_len;
/* find variable's value */
if ( pequal == plineend ) {
pvalue = plineend;
} else {
for ( pvalue = pequal + 1;
pvalue < plineend && (' ' == *pvalue || '\t' == *pvalue );
pvalue++ );
}
var_value_len = plineend - pvalue;
if ( (var_value_len + 1) > value_buf_size )
return -2;
memcpy(value_buf, pvalue, var_value_len);
value_buf[var_value_len] = '\0';
return var_value_len;
} |
|