在txt文件中实现四则运算, fgets, fputs, sprintf, sscanf, feof, strcat, strlen

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<string.h>
#define MAX 500
void write_file()
{
    FILE *fp;    
    fp = fopen("1.txt","w");
    if(NULL == fp
    {
        perror("write_file fopen");
        return;
    }
    fputs("10+10=\n",fp);
    fputs("10-10=\n",fp);
    fputs("10*10=\n",fp);
    fputs("10/10=\n",fp);
    fputs("20+10=\n",fp);
    fputs("10+5=\n",fp);  //注意最后一行也有\n,最后一行没有\n时候要格外注意读取时候使用feof会因为读到文件结束符而不打印直接跳出
    fclose(fp);
}

int calc(int a, int b, char ch)
{
    switc(ch)
    {
        case "+":
            return a+b;
        case "-":
            return a-b;
        case "*":
            return a*b;
        case "/":
            return a/b;
        default:
        return 0;        
        
    }
    return 0;    
}

void read_file()
{
    FILE *fp;
    char buf[1024],tmp[1024];
    fp = fopen("1.txt","r");
    if(NULL == fp
    {
        perror("read_file fopen");
        return;
    }
    while(1)
    {
        memset(buf,0,sizeof(buf));
        fgets(buf,sizeof(buf)-1,fp);//遇到\n,文件结束符,或者出错则结束读取。
        if(strlen(buf)>0)//避免buf没有读取到东西就操作。
        {
            int a, b;
            char ch;
            sscanf(buf,"%d%c%d\n",&a,&ch,%b);
            sprintf(buf,"%d%c%d=%d",a,ch,b,calc(a,b,ch));
            strcat(tmp,buf);            
        }
        if(feof(fp))//如果到文件结尾,则跳出循环
        {
            break;            
        }
        
        
    }
    fclose(fp);
    
    //关闭文件后,重新以W形式打开,目的是为了清空文件。
    fp = fopen("1.txt","w")'
    fputs(tmp,fp);
    fclose(fp);
    
    
}

int main()
{
    write_file();
    read_file();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Shayne_Lee/article/details/81459154