简体   繁体   English

计算 c 中文件的校验和

[英]Calculate checksum of a file in c

I try to calculate the checksum of the file in c.我尝试计算 c 中文件的校验和。

I have a file of around 100MB random and I want to calculate the checksum.我有一个大约 100MB 的随机文件,我想计算校验和。

I try this code from here: https://stackoverflow.com/a/3464166/14888108我从这里尝试这段代码: 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))"在这一行中“while (!feof(fp) && !ferror(fp))”

Any help will be appreciated.任何帮助将不胜感激。

The issue here is that you are not checking for the return value of fopen.这里的问题是您没有检查 fopen 的返回值。 fopen returns NULL if the file cannot be opened.如果文件无法打开,fopen 返回 NULL。 This means that fp is an invalid pointer, causing the segmentation fault.这意味着 fp 是一个无效指针,导致了段错误。

You should change the code to check for the return value of fopen and handle the error accordingly.您应该更改代码以检查 fopen 的返回值并相应地处理错误。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM