//文件版的四则运算 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> //进行文件四则运算的写入 void write_file() { FILE* fp = NULL; fp = fopen("D:/C_sum/test.txt", "w"); fputs("10/2=\n", fp); fputs("4-1=\n", fp); fputs("4*2=\n", fp); fputs("4+3=\n", fp); fclose(fp); } //利用switch语句求出四则运算的和 int Get_sum(int num1,char ch,int num2) { int sum = 0; switch(ch) { case '+': sum = num1 + num2; return sum; break; case '-': sum = num1 - num2; return sum; break; case '*': sum = num1 * num2; return sum; break; case '/': sum = num1 / num2; return sum; break; } } //开始拼接字符串然后导入文件 void read_file(char str1[],char result[]) { FILE* fp = NULL; int sum; int num1, num2; char ch; fp = fopen("D:/C_sum/test.txt", "r"); if (fp == NULL) { perror("OPEN file error:"); return; } while (1) { char temp[4096]; fgets(str1,4096, fp); //读取一行字符串到str1中 if (feof(fp)) break; sscanf(str1, "%d%c%d=\n", &num1, &ch, &num2);//利用sscanf()函数来按格式读取想要的数据 sum = Get_sum(num1,ch,num2); //调用求和函数来求出表达式的和 sprintf(temp, "%d%c%d=%d\n", num1, ch, num2,sum);//利用Sprintf函数来格式化得到想要的字符串 strcat(result, temp); //利用strcat函数来拼接字符串 } puts(result); fclose(fp); fp = fopen("D:/C_sum/test_sum.txt", "w");//最后打开文件来填写 fputs(result, fp); fclose(fp); } int main() { char result[4096] = { 0 }; char str1[4096] = { 0 }; read_file(str1,result); //write_file(); return 0; }