CEG220: Introduction to C Programming for Engineers – I

Section 2

 

Homework for Week 4

 

  1. Eileen is attempting to read a file using the following code, but always gets 0 as the answer. Assuming the file exists, what’s the most likely cause? How would you fix the code to solve this problem?

 

#include <stdlib.h>

#include <stdio.h>

#include <math.h>

 

...

 

{

double base = 0, exponent = 0, answer = 0;

FILE* pInputFile = fopen(“DataFile.txt”, “rb”);

 

do {

fread(&base, sizeof(base), 1, pInputFile);

fread(&exponent, sizeof(exponent), 1, pInputFile);

 

answer = pow(base, exponent);

 

printf(“%f raised to the %f power = %lf\n”, base, exponent, answer);

}

while( !feof(pInputFile) );

 

}

 

  1. After some debugging, Eileen decided to run her program using a different file, “Numbers.txt.” Somehow, some of her answers are incorrect; she gets output like this: “138.0000 raised to the 5.0000000 power = 2804362912.” What’s going on? Why isn’t she getting the right answer?

 

  1. Eileen’s program fails to output error messages when it hits an error condition – where something could go wrong. There are two types of errors – fatal and non-fatal. Fatal errors should cause the program to abort gracefully, notifying the user of what caused the fatal error. Non-fatal errors are errors where the program can recover gracefully (by asking the user again should they give bad input, etc.), notifying the user of the mistake. Where is the program likely to have fatal and non-fatal errors? Under what circumstances would such errors occur?