The main reason for getting Floating point exception is that you are accessing the file beyond its size.
In function total
and count
you are using the same pointer, so when done with total
the file pointer is at the end of file, and you are using the same in count
also.
you need to do fseek(file,SEEK_SET,0);
, to make the pointer point at the beginning.
and all of you block statements and functions are end by ;
, thats wrong.
I have corrected the program as a whole assuming that the contents of the file are just numbers like this 1 2 3 4 5 6
#include <stdio.h>
#define WORDS 100
int count(FILE *file){
int count = 0,n;
char word[WORDS];
// you need this to access the elements from start of the file
// comment below line causes sigfpe, Floating point exception
fseek(file,SEEK_SET,0);
printf(" position of fptr in count = %d\n",ftell(file));
while(fscanf(file,"%s",word)==1 ){
count++;
}
return count;
}
int total( FILE *file ){
int numbers, sum = 0;
int token;
// This is checked after number is read, will add the last number 2 times
//while(token != EOF){
while(1)
{
token = fscanf(file,"%d",&numbers);
printf("N = %d, token = %d\n", numbers, token);
if(token == EOF )
break;
sum += numbers;
}
printf(" position of fptr in total at the end = %d, sum = %d\n",ftell(file), sum);
return sum;
}
int main(){
char word[WORDS];
char theFile[WORDS];
FILE *fileptr;
printf("Enter the file name: ");
scanf("%s",theFile);
printf("Reading file %s...\n", theFile);
fileptr=fopen(theFile,"r");
if(fileptr == NULL){
fprintf(stderr,"ERROR: The file '%s' does not exist\n", theFile);
return 1;
}
int theSum = total(fileptr);
int theCount = count(fileptr);
//make sure to add a check that `theCount` is not zero
int theMean = theSum/theCount;
printf("Average weight: %d \n", theMean);
return 0;
}
CLICK HERE to find out more related problems solutions.