C 语言读取配置文件

(1) 准备好配置文件,在源码的路径下,叫config.ini,里面的内容是

[IPSite]
socketOneIp=127.0.0.1
socketOnePort=6001
socketTwoIp=127.0.0.1
socketTwoPort=6002

[Timer]
#单位 毫秒
timeCommand=5000
timePara=4000

(2) 定义函数

const int MAX_KEY_NUM = 128;
const int MAX_KEY_LENGTH = 1024;

char gKeys[MAX_KEY_NUM][MAX_KEY_LENGTH];

char *GetIniKeyString(char *title, char *key, char *filename)
{
    FILE *fp;
    int  flag = 0;
    char sTitle[32], *wTmp;
    char sLine[MAX_KEY_LENGTH];

    sprintf(sTitle, "[%s]", title);
    if (NULL == (fp = fopen(filename, "r")))
    {
        perror("fopen");
        return NULL;
    }

    while (NULL != fgets(sLine, MAX_KEY_LENGTH, fp))
    {
        /// 这是注释行  ///
        if (0 == strncmp("//", sLine, 2)) continue;
        if ('#' == sLine[0])              continue;

        wTmp = strchr(sLine, '=');
        if ((NULL != wTmp) && (1 == flag))
        {
            if (0 == strncmp(key, sLine, wTmp - sLine))  /// 长度依文件读取的为准  ///
            {
                sLine[strlen(sLine) - 1] = '\0';
                fclose(fp);
                return wTmp + 1;
            }
        }
        else
        {
            if (0 == strncmp(sTitle, sLine, strlen(sLine) - 1))  /// 长度依文件读取的为准  ///
            {
                flag = 1; /// 找到标题位置  ///
            }
        }
    }
    fclose(fp);
    return NULL;
}

(3) 调用过程

char * ipOne =  (char*)malloc(100 * sizeof(char));
    strcpy(ipOne,GetIniKeyString("IPSite", "socketOneIp", "config.ini"));    
    printf("ipOne is %s\n", ipOne);

    char * portOne  =  (char*)malloc(100 * sizeof(char));
    strcpy(portOne,GetIniKeyString("IPSite", "socketOnePort", "config.ini"));
    printf("portOne is %s\n", portOne);

    char * ipTwo  =  (char*)malloc(100 * sizeof(char));
    strcpy(ipTwo,GetIniKeyString("IPSite", "socketTwoIp", "config.ini"));
    printf("ipTwo is %s\n", ipTwo);

    char * portTwo  =  (char*)malloc(100 * sizeof(char));
    strcpy(portTwo,GetIniKeyString("IPSite", "socketTwoPort", "config.ini"));
    printf("portTwo is %s\n", portTwo);

(4)完美实现功能。

猜你喜欢

转载自blog.csdn.net/qq_14874791/article/details/108823552