读取配置文件[方式二]之使用Awk实现
一.配置文件样本:
- # user.conf
- # username age sex country
- tom 20 male us
- chen 22 female cn
二.使用shell的awk语言进行解析读取
例如:
获取 tom 的性别则可以使用这样的语句:
- cat user.conf | awk '/^tom[[:blank:]]+/ {print $3}'
三.在C语言中,我们如何将使用awk得到的结果交给一个变量呢?
一般就我而言采用两种方式,一种则是将得到的结果写入一个temp文件,然后直接读取到某个buffer中;另一种则是通过管道的方式写进去,再读出来,如
http://blog.csdn.net/wqf363/archive/2007/01/28/1496231.aspx讲到的例子一样。
- #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
