Home > database >  Calculate checksum of a file in c
Calculate checksum of a file in c

Time:12-03

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.

CodePudding user response:

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;
}

CodePudding user response:

The segmentation fault that you are experiencing is likely caused by the fact that you are not checking the return value of the fopen function, which is used to open the file for reading. If the fopen function fails, it will return NULL, and attempting to read from or write to a NULL file pointer can cause a segmentation fault.

To fix this issue, you can add a check for the return value of the fopen function, and handle the case where the file cannot be opened. For example, you could modify your code like this:

int CheckSumCalc(char * filename){
FILE *fp = fopen(filename, "rb");
if (fp == NULL) {
    // Handle error: file could not be opened
    return -1;
}

unsigned char checksum = 0;
while (!feof(fp) && !ferror(fp)) {
    checksum ^= fgetc(fp);
}
fclose(fp);
return checksum;
}

In this modified code, the fopen function is called to open the file for reading, and the return value is checked to see if it is NULL. If the file could not

  • Related