本demo 实现了 文件内容解析操作:
如 a 文件中若有 ” 1+2= “
则在b 文件中输出 “1+2=3”;
使用c标准语言实现
以供记录和学习
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *getSresult(const char *s,const char *sresult);
void move_newline(char *s);
int calc(const char *s);
int main(){
FILE *p= fopen("/home/renlikang/a.txt","r");
FILE *p1=fopen("/home/renlikang/b.txt","w");
if(p==NULL){
printf("open file failure\n");
return 0;
}
char buf[100]={0};
char sresult[100]={0};
while(!feof(p)){
memset(buf,0,100);
memset(sresult,0,100);
fgets(buf,100,p);
move_newline(buf);
fputs(getSresult(buf,sresult),p1);
}
fclose(p);
fclose(p1);
printf("end\n");
return 0;
}
char *getSresult(const char *s,const char *sresult){
int result=calc(s);
sprintf(sresult,"%s %d\n",s,result);
printf("%s\n",sresult);
return sresult;
}
void move_newline(char *s){
int len= strlen(s);
if(s[len-1]=='\n')
s[len-1]=0;
}
int calc(const char *s){
int len= strlen(s);
int index =0;
char num1[100]={0};
char num2[100]={0};
int int_num1=0;
int int_num2=0;
char opera=0;
while(s[index]){
if(s[index]=='+'||s[index]=='-'||s[index]=='*'||s[index]=='/'){
opera=s[index];
strncpy(num1,s,index);
strncpy(num2,s+index+1,len-index);
int_num1=atoi(num1);
int_num2=atoi(num2);
break;
}
index++;
}
switch(opera){
case '+':
return int_num1+int_num2;
case '-':
return int_num1-int_num2;
case '*':
return int_num1*int_num2;
case '/':
if(int_num2){
return int_num1/int_num2;
}else{
return 0;
}
//扩展运算符;
default:
return 0;
}
}