主要学习内容
- fputs()函数
- fgets()函数
- sprintf()函数
- sscanf()函数
- 以及文件的打开和关闭
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <Windows.h>
void write_file();
void read_file();
int main(void)
{
write_file();
getchar();
read_file();
system("pause");
return EXIT_SUCCESS;
}
void write_file() {
FILE* fp = fopen("test02.txt", "w");
if (fp == NULL)
{
perror("fopen error");
return -1;
}
fputs("10+4=\n", fp);
fputs("10-4=\n", fp);
fputs("10*4=\n", fp);
fputs("10/4=\n", fp);
fclose(fp);
}
void read_file() {
char buf[4096] = { 0 };
char result[4096] = { 0 };
char sum_ses[4096] = { 0 };
int a, b;
char ch;
FILE* fp = fopen("test02.txt", "r");
if (fp == NULL)
{
perror("fopen error");
return -1;
}
while (1) {
fgets(buf,4096,fp);
if (feof(fp))
{
break;
}
sscanf(buf, "%d%c%d=\n", &a, &ch, &b);
sprintf(result, "%d%c%d=%d\n", a, ch, b, calc(a,ch,b));
strcat(sum_ses, result);
}
fclose(fp);
printf("%s", sum_ses);
fp = fopen("test02.txt", "w");
fputs(sum_ses, fp);
fclose(fp);
}
int calc(int a, char ch, int b) {
switch (ch)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
break;
}
}