您的位置:首页 > 运维架构 > Shell

配置文件读取的n种方法

2007-01-28 15:57 525 查看

摘要

使用了下面5种方法来读取配置文件:1)字符串读写操作;2)xml解析配置文件;3)stl的读取配置文件封装类,很繁杂,但在大型配置文件中比较有用;4)shell语言的字符串匹配,这是最简单的;5)将1与4结合,shell与c的嵌套使用。

1字符串读写操作

测试文件[test.init]
#ini for path
[path]
dictfile = /home/tmp/dict.dat
inputfile= /home/tmp/input.txt
outputfile= /home/tmp/output.txt
#ini for exe
[exe]
user= winter       //user name
passwd= 1234567    #pass word
database= mydatabase
 


int main(int argc, char *argv[])




...{


    FILE* file;


    char input[100];


    unsigned short port;


    //fopen file to read


    //...


    while(1)




    ...{


        char* s =fgets(input, 100, file);


        if(s == NULL) break;


        if( (!strchr(input, '#') || (!strchr(input, '[') ) continue;


        if(!strncasecmp(input, "port", 4))




        ...{


            port = atoi(strchr(input, ''));


        }                                   


        if() //...




    }


    return 0;


}



2 xml解析配置文件法

基本思路:使用libxml2的一些tree解析函数,如:xmlReadFile, xmlDocGetRootElement, xmlStrcmp, xmlNodeGetContent。使用了一些属性:name(结点的名称), child(子结点), next(下一个结点)...
具体可参考本人另一篇blog: http://blog.csdn.net/wqf363/archive/2006/11/18/1394600.aspx

3 stl的读取配置文件封装类

基本思路:读取文件,将某个字符串开头的读入map里的key, 在其value值把其它字符串读入;读取时,查询key, 就获取到与key对应的value了。

4 shell的读取配置文件

# user.conf: configure file for user
# username age sex country
tom 20 male us
chen 22 female cn
 

例如,我们要获取 tom 的性别
可以用脚本这样来实现:
cat user.conf | awk '/^tom[[:blank:]]+/ {print $3}'

5 shell与C的嵌套使用


#include <stdio.h>


#include <sys/types.h>


#include <unistd.h>




static int my_system(const char* pCmd, char* pResult, int size);


int main(void)




...{


    char result[1025];


    my_system("cat user.conf | awk '/^tom[[:blank:]]+/ {print $3}'", result, 1025);


    printf("the result is: %s ", result);


    return 0;







static int my_system(const char* pCmd, char* pResult, int size)




...{


    int fd[2];


    int pid;


    int count;


    int left;


    char* p = 0;


    int maxlen = size-1;


    memset(pResult, 0, size);


    if(pipe(fd))




    ...{


        return -1;


    }


    if((pid = fork()) == 0)




    ...{// chile process


        int fd2[2];


        if(pipe(fd2))




        ...{


            return -1;


        }


        close(1);


        dup2(fd2[1],1);


        close(fd[0]);


        close(fd2[1]);


        system(pCmd);


        read(fd2[0], pResult, maxlen);


        pResult[strlen(pResult)-1] = 0;


        write(fd[1], pResult, strlen(pResult));


        close(fd2[0]);


        exit(0);


    }


    // parent process


    close(fd[1]);


    p = pResult;


    left = maxlen;




    while((count = read(fd[0], p, left))) ...{


        p += count;


        left -= count;


        if(left == 0)


        break;


    }


    close(fd[0]);


    return 0;


}



 

[denny@localhost testforc]$ ./a.out
the result is: male
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息