- 論壇徽章:
- 0
|
本人因做畢業(yè)設(shè)計(jì),學(xué)習(xí)C編程已有一個(gè)月了,但這段時(shí)間的學(xué)習(xí)進(jìn)展很慢,一直想多結(jié)交些同樣在學(xué)習(xí)unix下C編程的朋友。以下是本人寫的一個(gè)小程序,是用來讀取配置文件中的參數(shù)的。希望大家多多指正,同時(shí)也希望能起到拋磚引玉的作用,大家都發(fā)布一下自己的覺得有用的代碼。
我的聯(lián)系方式:zhguowen0103@hotmail.com (MSN:加好友時(shí)請(qǐng)注明“共同學(xué)C”。
說明:
本人開發(fā)環(huán)境:OS:AIX 5.2-03 編譯器:IBM(R) XL C Enterprise Edition V7.0 這段程序是用來在當(dāng)前目錄下一個(gè)文件中讀取disk_int and cpu_int兩個(gè)參數(shù)的值,要求文件的格式為:
…………
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";
/* 將要取的參數(shù)字符串讀入數(shù)組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;
}
/*計(jì)算數(shù)組temp_d中字符串的算術(shù)值*/
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);/*將文件中的內(nèi)容讀入數(shù)組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;
} |
|