百度空间 | 百度首页 
 
查看文章
 
读配置文件
2009-09-03 17:20
/* readconfig.c by R.wen(rwen2012@gmail.com), 20090903 */

/* read file like this: (net-eth0.txt)

MODE  =  static
IPADDR=192.168.9.159
NETMASK=255.255.255.0
GATEWAY=192.168.9.1

*/

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>


int readline(int fd, char *buf)
{
char c;
int n;

for (;;) {
n = read(fd, &c, 1);
if (n == 1) {
if (c != '\n' && c !=' ') *buf++ = c;
else if (c == ' ') continue;
else break; /* '\n' */
} else
return 0;
}

*buf = '\0';           
return 1;
}


typedef int (*fn_t)(char *name, char *value, void *arg);
int parse(char *buf, fn_t fn, void *arg)
{
char *s;
char *name, *value;   

name = buf;
s = strchr(buf, '=');
if (!s) return -1;
value = s;

*s = '\0';
value++;

fn(name, value, arg);

return 0;
}


typedef struct ipconf {
char mode[64];
char ipaddr[64];   
char netmask[64];
char gateway[64];
} ipconf_t;

int getipconf(char *name, char *value, void *arg)
{
//    char *name, *value;
int ret;

ipconf_t *ipc = (ipconf_t *)arg;

if (!strcmp("MODE", name)) {
strcpy(ipc->mode, value);
} else if (!strcmp("IPADDR", name)) {
strcpy(ipc->ipaddr, value);
} else if (!strcmp("NETMASK", name)){
strcpy(ipc->netmask, value);
} else if (!strcmp("GATEWAY", name)) {
strcpy(ipc->gateway, value);
} else
printf("not reconigse: name = %s, value = %s\n", name, value);

return 0;
}


int main(void)
{
int fd;
char buf[512];
ipconf_t ipc;
int ret;

fd = open("net-eth0.txt", O_RDONLY);

for (;;) {
ret = readline(fd, buf);
if (ret <= 0)
break;

parse(buf, getipconf, &ipc);
}

printf("ipc->mode: %s\n", ipc.mode);
printf("ipc->ipaddr: %s\n", ipc.ipaddr);
printf("ipc->netmask: %s\n", ipc.netmask);
printf("ipc->gateway: %s\n", ipc.gateway);

return 0;
}




类别:c语言实践 | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu