使用C语言解析INI文件


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_
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值