I think you are right. here is a piece of my code for this implementation. Any comment?
Code:
unsigned char average(const char *filename){
unsigned int BLOCK_SIZE=512;
unsigned int nlen=0, nround=0;
unsigned char avg = 0;
FILE *fp;
unsigned char tmp[512];
if ( (fp = fopen(filename,"r")) == NULL){
printf("\nThe file did not open\n.");
return 255;
}
while(!feof(fp)){
if(fread(tmp, 1, BLOCK_SIZE, fp)){
nlen+=BLOCK_SIZE;
nround++;
}else{
BLOCK_SIZE=BLOCK_SIZE/2;
}
}
avg=(unsigned char)(nlen/nround);
return avg;
}
Originally Posted by
Sebastiani
An average is simply all the values added together and then divided by the number of values. Problem is, adding a bunch of bytes together using a single byte will likely overflow, so you'll either need a larger data type or use perhaps a clever mathematical technique to overcome that issue.
>> unsigned char avg = 1;
You should set that to 0.
>> while(!feof(fp))
You're checking the end-of-file condition too early, use that to break out of the loop *after* you have read the next value but *before* you attempt to use the value.