Chinaunix首页 | 论坛 | 博客
  • 博客访问: 347113
  • 博文数量: 78
  • 博客积分: 3380
  • 博客等级: 中校
  • 技术积分: 857
  • 用 户 组: 普通用户
  • 注册时间: 2010-06-16 19:39
文章分类

全部博文(78)

文章存档

2011年(31)

2010年(47)

分类: C/C++

2010-07-14 18:18:09

配置文件读取一:

现有一文件.myprofile,里面内容为环境变量如:path=/bin:/sbin:/usr/bin:/usr/sbin;

要求截取路径为

/bin

/sbin

/usr/bin

/usr/sbin

实现代码:

实现一:

int init_envi(char *buf[])

{

char *token;

int fd;

int i=0;

fd=open("./myprofile",O_RDONLY);

if(fd==-1)

{

perror("open error!");

exit(1);

}

memset(str_buf,'\0',sizeof(str_buf));

read(fd,str_buf,sizeof(str_buf));

str_buf[strlen(str_buf)-1]='\0';

token=strtok(str_buf,"=");

buf[i]=token;

while(token!=NULL)

{

token=strtok(NULL,":");

buf[++i]=token;

// printf("the buf[%d] is =%s\n",i,buf[i]);

}

buf[i]=NULL;

return 0;

}

实现二:

void env_init()

{

FILE *fp;

int i=0;

char *p=env_buf;

if((fp=fopen("./myprofile","r"))==NULL)

{

perror("open my_profile error");

exit(1);

}

fgets(env_buf,200,fp);

fclose(fp);

printf("env_buf=%s\n",env_buf);

p=strstr(env_buf,"PATH=")+5;

argv_env[i++]=p;

while(*p!='\0')

{

if( (*p==':') && (*(p+1)!='\0'))

{

argv_env[i++]=p+1;

*p='\0';

}

p++;

}

argv_env[i]=NULL;

i=0;

while(argv_env[i]!=NULL)

{

printf("argv_env[%d]=%s\n",i,argv_env[i++]);

}

}

阅读(5055) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~