您的位置:首页 > 编程语言 > C语言/C++

使用C语言解析INI文件

2009-04-30 13:48 357 查看
2006-12-30 22:12
/*

* File: inifile.h

* Read INI File

*/

#ifndef _INIFILE_H_

#define _INIFILE_H_

#include <stdio.h>

#include <string.h>

/*

* char* GetInitKey(FileName, Section, Key)

* Return Key=>Value

* Ex:

*

* config.ini

* [config]

* dbhost=localhost

*

* Usage:

* char dbhost[20];

* strcpy(dbhost,GetInitKey("config.ini", "config", "dbhost"));

*

* History:

* Chen QunShan@20061010 (chqs_at_sina.com)

* Handle comment line, duplicate section,

* similar key, partly same key, key string existing

* in value, trim left space char

* and the last char is EOF.

*/

char *GetInitKey(char *filename, char *title, char *key)

{

FILE *fp;

char tmpLine[1024];

int rtnval;

int i = 0;

int flag = 0;

char *tmp;

static char tmpstr[1024];

if ((fp = fopen(filename, "r")) == NULL) {

return "have no such file";

}

while (!feof(fp)) {

rtnval = fgetc(fp);

if (rtnval == EOF) {

tmpLine[i++] = 0;

} else {

tmpLine[i++] = rtnval;

}

if (rtnval == '/n' || rtnval == EOF) {

tmpLine[--i] = 0;

i = 0;

if (tmpLine[0] == '/0' || strchr("#;", tmpLine[0]) != NULL)

continue; // Skip null line or comment line

if (tmpLine[0] == '[') {

tmp = NULL;

if (flag == 1) {

// Meet next section

#ifdef PROCESS_DUP_SECTION // INI file exist duplicate section

flag = 0;

#else

break; // Skip other context

#endif

}

} else {

tmp = strchr(tmpLine, '=');

}

if ((tmp != NULL) && (flag == 1)) {

char *p;

*tmp = '/0'; // erase '=', spilte Key and Value

p = strstr(tmpLine, key);

if (p != NULL) {

if (p > tmpLine && strchr(" /t", *(p - 1)) == NULL)

continue; // exist prefix, mishit key

p += strlen(key);

if (*p == '/0' || strchr(" /t", *p) != NULL) {

tmp++; // Skip '='

while (*tmp == ' ' || *tmp == '/t')

tmp++; // Skip left lead ' ' or '/t'

strcpy(tmpstr, tmp);

fclose(fp);

return tmpstr;

}

}

} else {

strcpy(tmpstr, "[");

strcat(tmpstr, title);

strcat(tmpstr, "]");

if (strcmp(tmpstr, tmpLine) == 0) {

flag = 1;

}

}

}

if (rtnval == EOF) {

break;

}

} // end of while

fclose(fp);

return "";

}

/*--------------*

* Test Case: *

*--------------*

config.ini

;[test]

#p2= 789

;p2= 9

p2 = 456

[test]

p3 = p2

pp2= 45

p2 = "456"

[ip]

portexam=777

[user]

port=666

*--------------*/

#endif //_INIFILE_H_
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: