- 论坛徽章:
- 0
|
本人因做毕业设计,学习C编程已有一个月了,但这段时间的学习进展很慢,一直想多结交些同样在学习unix下C编程的朋友。以下是本人写的一个小程序,是用来读取配置文件中的参数的。希望大家多多指正,同时也希望能起到抛砖引玉的作用,大家都发布一下自己的觉得有用的代码。
我的联系方式:zhguowen0103@hotmail.com (MSN:加好友时请注明“共同学C”。
说明:
本人开发环境:OS:AIX 5.2-03 编译器:IBM(R) XL C Enterprise Edition V7.0 这段程序是用来在当前目录下一个文件中读取disk_int and cpu_int两个参数的值,要求文件的格式为:
…………
disk_int 30
cpu_int 5
…………
程序代码:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
char temp_d[8];
char temp[4096];
char *p;
int temp_i=0;
const char tmp1[8]="cpu_int";
const char tmp2[9]="disk_int";
/* 将要取的参数字符串读入数组temp_d中 */
void get_str(char *p)
{
int i=0;
while ((*p>='0')&&(*p<='9'))
{
temp_d=*p;
temp_i=i;
i++;
p++;
temp_d='\0';
}
return;
}
/*计算数组temp_d中字符串的算术值*/
int get_value()
{
int i=0;
int j=0;
for (i=0;i<=temp_i;i++)
{
j*=10;
j+=temp_d-48;
}
return j;
}
int main(int argc, char* argv[])
{
int fd,aa;
if (argc != 2)
{
printf("Only one file can be input");
return;
}
if ((fd=open(argv[1],O_RDONLY))== -1)
{
printf("cannot open file1");
exit ( 0 ) ;
}
read (fd,temp,4096);/*将文件中的内容读入数组temp中*/
p=strstr(temp,tmp1);
while(*p!=' '&&*p!='=')
p++;
p++;
get_str(p);
aa=get_value();
printf("cpu_int =%d\n",aa);
p=strstr(temp,tmp2);
while(*p!=' ')
p++;
p++;
get_str(p);
aa=get_value();
printf("disk_int =%d\n",aa);
return;
} |
|