zoukankan      html  css  js  c++  java
  • 自定义配置文件读取

    读取配置文件 以#开头的行是注释行  键和值 用空格分开 一行一个键值对

    如:

    #  注释

    key1 2

    key2  aab

    增加结构体 Config的成员key(自行定义的变量名)存变量, 添加代码

            if( strcasecmp(key,"key")==0 ) {
                strncpy(sConfig->key,val,128);
            }
    获取值。
    typedef struct 
    {
        int port;
        char rootDir[128];
    } Config;
    /**
     * read config from httpd.conf 
     * parameters : file name 
     * return 
     */
    /**
     * [readCfg read conf  key val ]
     * @param filename [file name ]
     * @param sConfig  [config struct ]
     */
    void readCfg(char *filename, struct Config* sConfig)
    {
        FILE *pf = NULL;
        char buf[2048];
        int i = 0,j = 0;
        char key[128];
        char val[128];
    
        pf = fopen(filename, "r+");
        if (NULL==pf){
            perror("open config file error. use default config.");
            return;
        }
        while(!feof(pf)) {
            fgets(buf,2048,pf);
            i = 0; j = 0;
            printf("%s
    ", buf);
            // get key 
            while (!isspace(buf[i]) && (i < strlen(buf) - 1))
            {
                key[j] = buf[i];
                i++;
                j++;
            }
            key[j] = 0;
            printf("%s
    ", key);
    
            if ('#'==key[0]) continue;
            // get val
            i++; j=0;
            while (!isspace(buf[i]) && (i < strlen(buf) - 1))
            {
                val[j] = buf[i];
                i++;
                j++;
            }
            val[j] = 0;
            printf("%s
    ", val);
    
            if( stricmp(key,"port")==0 ) {
                sConfig->port = atoi(val);
            }
    
            if( stricmp(key,"rootDir")==0 ) {
                strncpy(sConfig->rootDir,val,128);
            }
        }
        fclose(pf);
    }
  • 相关阅读:
    集合set() 和 深浅copy
    Python 数据类型的操作——字典
    Python()- 面向对象
    面向对象的软件开发
    Python数据类型的操作——列表、元组
    Python 数据类型的操作——字符串
    Linux下386中断处理
    任务的休眠与唤醒
    Linux下SIGSTOP的特殊特征和实现
    内核线程对信号的处理策略
  • 原文地址:https://www.cnblogs.com/swing07/p/10527297.html
Copyright © 2011-2022 走看看