1. 程式人生 > >用C語言獲取配置的值

用C語言獲取配置的值

在嵌入式開發中,我們經常要讀取配置檔案,且裡面的值形式為“name=value”,用下面的程式碼可以獲取這樣的值,

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>


#define FALSE (0)
#define TRUE  (1)

unsigned int process_config_vars(char *varbuf, unsigned int len, char *pickbuf, char *param)
{
	int findNewline, changenewline=FALSE, pick=FALSE;
	int column;
	unsigned int n, pick_column=0;

	findNewline = FALSE;
	column = 0;

	for (n = 0; n < len; n++) {
		if (varbuf[n] == '\r')
			continue;
		if ((findNewline || changenewline) && varbuf[n] != '\n')
			continue;
		findNewline = FALSE;
		if (varbuf[n] == '#') {
			findNewline = TRUE;
			continue;
		}
		if (varbuf[n] == '\\') {
			changenewline = TRUE;
			continue;
		}
		if (!changenewline && varbuf[n] == '\n') {
			if (column == 0)
				continue;
			column = 0;
			continue;
		}
		if (changenewline && varbuf[n] == '\n') {
			changenewline = FALSE;
			continue;
		}
		if (!memcmp(&varbuf[n], param, strlen(param)) && column==0) {
			pick = TRUE;
			column = strlen(param);
			n += column;
			pick_column = 0;
		} else {
			if (pick && column==0)
				pick = FALSE;
			else
				column++;
		}        if (pick) {
			if (varbuf[n] == 0x9)
				continue;
			if (pick_column>0 && pickbuf[pick_column-1]==' ' && varbuf[n]==' ')
				continue;
			pickbuf[pick_column] = varbuf[n];
			pick_column++;
		}
	}

	return pick_column;
}

int main(int argc,char *argv[])
{
	char *path = "config.txt";
	char buf[4096] = {0};
	char value[1024] = {0};
	int fd = -1,len = 4096,ret = -1;

	fd = open(path,O_RDONLY);
	if(fd < 0) {
		printf("open %s failed.\n",path);
		return -1;
	}

	ret = read(fd,buf,len);

	ret = process_config_vars(buf,len,value,"name=");
	if(ret > 0)
			printf("ret = %d,value=%s\n",ret,value);
	
	close(fd);
}