Code:
#include <stdio.h>
#define FILENAME1 "CommandsProj1.dat"
#define FILENAME2 "storedData.dat"
//function prototype
void calculations(FILE*data1, FILE*data2, char ch);
int main()
{
//variables for main
char initials[3];
char ch;
//initialize these variables
FILE*data1;
FILE*data2;
//open file to be read
data1 = fopen(FILENAME1, "r");
//open file to be written
data2 = fopen(FILENAME2, "w");
//test if file is there or not, if not, then prints error
if(data1 == NULL)
{
printf("Error. File not loaded.\n");
fprintf(data2, "Error. File not loaded.\n");
}
else
{
//reads the file, get initial, prints out the initial
fscanf(data1, "%s", initials);
printf("Initial is: %s\n", initials);
fprintf(data2, "Initial is: %s\n", initials);
//get the command from the file
while(data1)
{
fscanf(data1, "%c", &ch);
if(ch == 'H')
{
printf("Caculator Commands:\n\n");
printf(" + [Add Integers]\n");
printf(" - [Subtract Integers]\n");
printf(" * [Multiply Integers]\n");
printf(" / [Divide Integers]\n\n");
}
else if(ch == 'Q')
{
fclose(data1);
fclose(data2);
return(0);
}
else
calculations(data1, data2, ch);
}
}
return(0);
}
void calculations(FILE*data1, FILE*data2, char ch)
{
int i, j, answer;
fscanf(data1, "%d %d", &i, &j);
switch(ch)
{
case '*':
answer = i * j;
printf("%d * %d = %d\n", i, j, answer);
fprintf(data2, "%d * %d = %d\n", i, j, answer);
break;
case '/':
answer = i / j;
if(j == 0)
{
printf("Value is undefined.");
fprintf(data2, "Value is undefined.");
}
else
{
printf("%d / %d = %d\n", i, j, answer);
fprintf(data2,"%d / %d = %d\n", i, j, answer);
}
break;
case '+':
answer = i + j;
printf("%d + %d = %d\n", i, j, answer);
fprintf(data2,"%d + %d = %d\n", i, j, answer);
break;
case '-':
answer = i - j;
printf("%d - %d = %d\n", i, j, answer);
fprintf(data2, "%d - %d = %d\n", i, j, answer);
break;
}
}