#include"main.h"
static void deal_with_array(my_array *buf,char s[]) { char *pstart=NULL; char *pend=NULL; char *psign=NULL; psign=pstart=s; pend=&s[strlen(s)]; printf("pstart:%s\n",pstart); char tmp1[64]; char tmp2[64]; int i; for(i=0;s[i]!='\0';i++){ if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){ psign=&s[i]; strncpy(tmp1,s,psign-pstart+1); buf->first_arg=atoi(tmp1); strncpy(tmp2,psign+1,pend-psign); buf->second_arg=atoi(tmp2); buf->sign=s[i]; printf("firest:%d\tsecond:%d\tsign:%c\n",buf->first_arg,buf->second_arg,buf ->sign); break; } } }static int get_result(int arg1,char sign,int arg2) { int result=0; switch(sign){ case '+':result=arg1+arg2;break; case '-':result=arg1-arg2;break; case '*':result=arg1*arg2;break; case '/':if(arg1>=arg2)result=arg1/arg2;break; default:break; } return result; }static int FileToStore(char *buf,char *file) { FILE *fp; if(NULL==file){ fprintf(stderr,"[%s][%d]NO file!\n",__func__,__LINE__); return 1; } if((fp=fopen(file,"r"))==NULL){ fprintf(stderr,"[%s][%d]fopen error!\n",__func__,__LINE__); return 1; } if(fread(buf,1,BUFFSIZE,fp)==0){ fprintf(stderr,"[%s][%d]fread error!\n",__func__,__LINE__); return 1; } fclose(fp); return 0; } static int StoreToFile(char *buf,int len,char *file) { FILE *fp; if(NULL==file){ fprintf(stderr,"[%s][%d]NO file!\n",__func__,__LINE__); return 1; } if((fp=fopen(file,"w+"))==NULL){ fprintf(stderr,"[%s][%d]fopen error!\n",__func__,__LINE__); return 1; } if(fwrite(buf,1,len,fp)==0){ fprintf(stderr,"[%s][%d]fwrite error!\n",__func__,__LINE__); return 1; } fclose(fp); return 0; } int main(int argc,char **argv) { char buf[BUFFSIZE]; char read_buf[BUFFSIZE]; int len; int result; my_array To_store; char pout[64]; int tmp=0; char tmp_buf[64]; char *pp[10]; int n=1; if(3!=argc){ fprintf(stderr,"Usage:\n%s destfile sourcfile\n",argv[0]); exit(1); } FileToStore(read_buf,argv[2]); int j,k; pp[0]=read_buf; for(j=0;read_buf[j]!='\0';j++){ if('\n'==read_buf[j]){ pp[n]=&read_buf[j]; n++; } }
int num_line=0; char *pbuf=read_buf; while(*pbuf++!='\0'){ if(*pbuf=='\n') num_line++; } int m=0; for(k=0;k<num_line;k++){ strncpy(tmp_buf,pp[m],pp[m+1]-pp[m]); int s; m++; deal_with_array(&To_store,tmp_buf); if(!To_store.sign){ fprintf(stderr,"deal_with_array error!\n"); exit(2); } len=sizeof(To_store); fprintf(stderr,"[%s][%d]file1_size:[%d]",__func__,__LINE__,len); printf("firest:%d\tsecond:%d\tsign:%c\n",To_store.first_arg,To_store.second_ arg,To_store.sign); if((result= get_result(To_store.first_arg,To_store.sign,To_store.second_arg) )==0){ fprintf(stderr,"get_result error!\n"); exit(3); } printf("Result:%d\n",result); sprintf(pout,"%i",result); strcat(buf,pout);
strcat(buf,"\n"); memset(&To_store,0x00,sizeof(To_store)); memset(pout,0x00,sizeof(pout)); } StoreToFile(buf,strlen(buf),argv[1]); exit(0); }
|