你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

读取配置文件[方式二]之使用Awk实现

2022/6/24 19:47:17

读取配置文件[方式二]之使用Awk实现

分类: C++ Linux系统编程 C 2010-03-11 09:52 368人阅读 评论(0) 收藏 举报

一.配置文件样本:

[c-sharp] view plain copy
  1. # user.conf  
  2. # username age sex country  
  3. tom 20 male us  
  4. chen 22 female cn  

二.使用shell的awk语言进行解析读取

例如:

获取 tom 的性别则可以使用这样的语句:

[c-sharp] view plain copy
  1. cat user.conf | awk '/^tom[[:blank:]]+/ {print $3}'  

三.在C语言中,我们如何将使用awk得到的结果交给一个变量呢?

一般就我而言采用两种方式,一种则是将得到的结果写入一个temp文件,然后直接读取到某个buffer中;另一种则是通过管道的方式写进去,再读出来,如

http://blog.csdn.net/wqf363/archive/2007/01/28/1496231.aspx讲到的例子一样。

[c-sharp] view plain copy
  1. #include <stdio.h>  
  2. #include <sys/types.h>  
  3. #include <unistd.h>  
  4.   
  5. static int my_system(const char* pCmd, char* pResult, int size);  
  6. int main(void)  
  7. ...{  
  8.     char result[1025];  
  9.     my_system("cat user.conf | awk '/^tom[[:blank:]]+/ {print $3}'", result, 1025);  
  10.     printf("the result is: %s ", result);  
  11.     return 0;  
  12. }   
  13.   
  14. static int my_system(const char* pCmd, char* pResult, int size)  
  15. ...{  
  16.     int fd[2];  
  17.     int pid;  
  18.     int count;  
  19.     int left;  
  20.     char* p = 0;  
  21.     int maxlen = size-1;  
  22.     memset(pResult, 0, size);  
  23.     if(pipe(fd))  
  24.     ...{  
  25.         return -1;  
  26.     }  
  27.     if((pid = fork()) == 0)  
  28.     ...{// chile process  
  29.         int fd2[2];  
  30.         if(pipe(fd2))  
  31.         ...{  
  32.             return -1;  
  33.         }  
  34.         close(1);  
  35.         dup2(fd2[1],1);  
  36.         close(fd[0]);  
  37.         close(fd2[1]);  
  38.         system(pCmd);  
  39.         read(fd2[0], pResult, maxlen);  
  40.         pResult[strlen(pResult)-1] = 0;  
  41.         write(fd[1], pResult, strlen(pResult));  
  42.         close(fd2[0]);  
  43.         exit(0);  
  44.     }  
  45.     // parent process  
  46.     close(fd[1]);  
  47.     p = pResult;  
  48.     left = maxlen;  
  49.     while((count = read(fd[0], p, left))) ...{  
  50.         p += count;  
  51.         left -= count;  
  52.         if(left == 0)  
  53.         break;  
  54.     }  
  55.     close(fd[0]);  
  56.     return 0;  
  57. }  

 

执行结果:

[c-sharp] view plain copy
  1. [denny@localhost testforc]$ ./a.out   
  2. the result is: male