#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int f_calc(int p_v1, char p_sign, int p_v2) {
switch (p_sign) {
case '+':
return p_v1 + p_v2;
case '-':
return p_v1 - p_v2;
case '*':
return p_v1 * p_v2;
case '/': //这个地方有一个致命的地方
if (!p_v2) {
return -1;
}
else {
return p_v1 / p_v2;
}
}
}
void main() {
FILE* l_fp_read = fopen("1.txt", "r");
if (!l_fp_read) {
printf("打开读文件失败!\n");
system("pause");
return;
}
int l_last_position = NULL;
char l_read_line[50] = { NULL };
char l_write_line[50] = { NULL };
int * p_save = NULL;
int l_count = NULL;
while (!feof(l_fp_read)) {
fgets(l_read_line, sizeof(l_read_line), l_fp_read);
int l_this_position = ftell(l_fp_read);
if (l_this_position != l_last_position) {
l_last_position = l_this_position;
int l_v1, l_v2;
char l_sign;
int l_result;
sscanf(l_read_line, "%d%c%d=", &l_v1, &l_sign, &l_v2);
l_result = f_calc(l_v1, l_sign, l_v2);
sprintf(l_write_line, "%d%c%d=%d\n", l_v1, l_sign, l_v2, l_result);
//在C语言中,只要是系统内置的函数,如果里面包含scanf这个关键字.
//你一定要使用取地址符号才能正常使用.
l_count++;
p_save = (int *)realloc(p_save, l_count*sizeof(int));
int l_sizecount = strlen(l_write_line) + 1;
p_save[l_count - 1] = (int)calloc(l_sizecount, sizeof(char));
strcpy((char *)p_save[l_count - 1], l_write_line);
}
}
FILE* l_fp_write = fopen("1.txt", "w");
if (!l_fp_write) {
printf("打开写文件失败!\n");
system("pause");
return;
}
for (size_t i = 0; i < l_count; i++) {
fputs((char *)p_save[i], l_fp_write);//ctrl+J
free((char *)p_save[i]);
}
free(p_save);
fclose(l_fp_read);
printf("\n自动答题工作完成\n");
system("pause");