Files
Laboratori-TDP/Laboratorio 1/calcolatricefile.c
2024-03-22 17:14:57 +01:00

61 lines
1.2 KiB
C

#include <stdio.h>
int main()
{
FILE *fp_read, *fp_write;
char operation;
float op1, op2, res;
if ((fp_read = fopen("./Operations.txt", "r")) == NULL)
{
printf("Error opening file\n");
return 1;
}
if ((fp_write = fopen("./Results.txt", "w")) == NULL)
{
printf("Error opening file\n");
return 2;
}
while (!feof(fp_read))
{
fscanf(fp_read, " %c %f %f", &operation, &op1, &op2);
if (!feof(fp_read))
{
switch (operation)
{
case '+':
res = op1 + op2;
break;
case '-':
res = op1 - op2;
break;
case '*':
res = op1 * op2;
break;
case '/':
if (op2 == 0)
{
printf("Error: divide by zero\n");
return 3;
}
res = op1 / op2;
break;
default:
printf("Error: invalid operation\n");
return 1;
}
fprintf(fp_write, "%c %.2f\n", operation, res);
}
}
fclose(fp_read);
fclose(fp_write);
return 0;
}