Reputation: 141
I try to calculate the checksum of the file in c.
I have a file of around 100MB random and I want to calculate the checksum.
I try this code from here: https://stackoverflow.com/a/3464166/14888108
int CheckSumCalc(char * filename){
FILE *fp = fopen(filename,"rb");
unsigned char checksum = 0;
while (!feof(fp) && !ferror(fp)) {
checksum ^= fgetc(fp);
}
fclose(fp);
return checksum;
}
but I got a Segmentation fault. in this line "while (!feof(fp) && !ferror(fp))"
Any help will be appreciated.
Upvotes: 1
Views: 1092
Reputation: 9857
The issue here is that you are not checking for the return value of fopen. fopen returns NULL if the file cannot be opened. This means that fp is an invalid pointer, causing the segmentation fault.
You should change the code to check for the return value of fopen and handle the error accordingly.
int CheckSumCalc(char * filename){
FILE *fp = fopen(filename,"rb");
if(fp == NULL)
{
//handle error here
return -1;
}
unsigned char checksum = 0;
while (!feof(fp) && !ferror(fp)) {
checksum ^= fgetc(fp);
}
fclose(fp);
return checksum;
}
Upvotes: 1