In: Computer Science
Write C functions to do each of the following. Make sure your function has exactly the same name, parameters, and return type as specified here. Please place all of the functions in a single .c file and write a main() to test them.
int process(const char *input_filename, const char *output_filename) — reads the file named input_filename and processes it, putting results in output_filename. The input file consists of lines of the form "number operation number," for example:
15 - 4 3.38 / 2.288 2 ^ -5 35.2 + 38
The possible operations are +, -, *, /, and ^ (power). Your function should calculate the value of each line's expression and save it (one to a line) to the output file. For example, the input file shown above would result in an output file of
11.000000 1.477273 0.031250 73.200000
The return value of the function should be the number of calculations that it did (4 for this example file).
(Hints: fscanf() returns the constant value EOF when the end of file is reached. The pow(x, y) function defined in <math.h> calculates xy; you will need to add -lm to the command line when compiling your code to link the math library.)
#include<stdio.h>
#include<math.h>
//function to process input file
int process(const char *input_filename, const char
*output_filename) {
//declaring file pointers and opeing file in
appropriate modes
FILE *inp;
inp = fopen(input_filename, "r");
FILE *outp;
outp = fopen(output_filename, "w");
double op1 = 0, op2 = 0;
char opr
//reading the input file
while(fscanf(inp, "%lf %c %lf", &op1, &opr,
&op2) == 3) {
double res;
//doing operation as per the
operator found
switch(opr) {
case '+':
res = op1 + op2;
break;
case '-':
res = op1 - op2;
break;
case '*':
res = op1 * op2;
break;
case '/':
res = op1 / op2;
break;
case '^':
res = pow(op1, op2);
break;
}
//writing the result onto the
output file.
fprintf(outp, "%lf\n", res);
}
fclose(inp);
fclose(outp);
}
main() {
process("input.txt", "output.txt");
}
Input.txt
15 - 4 3.38 / 2.288 2 ^ -5 35.2 + 38
output.txt
11.000000
1.477273
0.031250
73.200000