Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// MACROS
#define ADD(n7,n8) ((n7)+(n8))
#define SUB(n1,n2) ((n1)-(n2))
#define MUL(n1,n2) ((n1)*(n2))
#define DIV(n1,n2) ((n1)/(n2))
//MACRO FORMAT for saving
#define FORMAT fprint(fPtr"%f%f%f",CalResult.n1,CalResult.n2,CalResult.result)
// declare struct CalResult
struct cal3field
{
double n1;
double n2;
double result;
} CalResult;
void main(int argc, char *argv[])
{
FILE *fPtr; /* fPtr = cal_result.txt file pointer */
char op[2] = " ";
double result = 0, n1 = 0, n2 = 0;
strcpy(op,argv[2]);
//open the file
/* opens the file. Exit program if was unable to create file */
if ( ( fPtr = fopen( "cal_result.txt", "a" ) ) == NULL ) {
printf( "File could not be opened\n" );
}
else {
//printf( "Enter EOF to end input.\n" );
/* get operator */
n1 = atof(argv[1]);
/* get first argument */
n2 = atof(argv[3]);
/* get second argument */
switch(op[0])
{
case '+':
result = ADD(n1,n2);
//PRINT;
break;
case '-':
result = SUB(n1,n2);
//PRINT;
break;
case '*':
case 'x':
case 'X':
result = MUL(n1,n2);
//PRINT;
break;
case '/':
//case '\\':
if(n2 != 0.0) result = DIV(n1,n2);
//PRINT;
break;
default: puts("Wrong operator entered");
}// end case
// Structure variable CalResult holds values of n1, n2, and result
CalResult.n1 = n1;
CalResult.n2 = n2;
CalResult.result = result;
fprintf( fPtr, "%f %f %f\n", (CalResult.n1),(CalResult.n2),(CalResult.result)
);
/* write n1, n2 and result into file with fprintf */
//fprintf( fPtr, "%f %f %f\n", n1, n2, result ); // write data
//fprintf(fPtr, FORMAT); // write data
//} /* end while */
fclose( fPtr ); /* fclose closes file */
} /* end else */
//Read the file
/* fopen opens file; exits program if file cannot be opened */
if ( ( fPtr = fopen( "cal_result.txt", "r" ) ) == NULL ) {
printf( "File could not be opened\n" );
} // end if
else { // read n1, n2 and result from file *
printf("Reading file\n");
printf( "%-10s%-13s%s\n", "n1", "n2", "result" );
//fscanf( fPtr, "%lf%lf%lf", &CalResult.n1, &CalResult.n2 &CalResult.result);
//printf( "%f %f %f\n ", CalResult.n1 , CalResult.n2, CalResult.result);
// while not end of file
//while ( !feof( fPtr ) ) {
printf( "%-10f%-13f%7.2f\n", n1, n2, result );
fscanf( fPtr, " %lf %lf %lf", &CalResult.n1, &CalResult.n2
,&CalResult.result );
//} // end while
fclose( fPtr ); // fclose closes the file
} // end else
} /* end main */