C语言中CRC16的文件validation混乱

在这里,我想知道如何为任何类型的文件实现计算CRC16,

在这里我对CRC16及其代码逻辑有所了解。 在这里我做了一个函数,它将文件路径作为输入并找出它的CRC值。 这里我在这个函数中传递文件名,这个函数计算这个文件的CRC值。 但我想计算所有类型的文件,如.tar,.tar.gz,.txt,.bin,.scr etc

所以在这里我打开所有文件和"rb"模式,并逐个字符,并以正确的方式找出CRC值? 可能是我错过了这个。 它适用于.txt和所有其他文件,但它会在.tar, .tar.gz类型文件中产生问题。 因为这里我有一个文件,它是890 MB ,它的名字是file.tar.gz ,它需要203 file.tar.gz ,我有其他文件,它是382 MB ,它的名字是file2.tar它取6097850.000000 Microseconds对我来说难以置信如何可能?

我的问题是这些

 1 Some thing problem in my CRC code ? 2 Problem in reading file data style, may be i am reading file data in wrong manner for .tar.gz. 

这是我的代码:

 int CRC16(const char* filePath) { //Declare variable to store CRC result. unsigned short result; //Declare loop variables. int intOuterLoopIndex, intInnerLoopIndex, nLen; result = 0xffff; //initialize result variable to perform CRC checksum calculation. //Store message which read from file. //char content[2000000]; //Create file pointer to open and read file. FILE *readFile; //Use to read character from file. char readChar; //open a file for Reading readFile = fopen(filePath, "rb"); //Checking file is able to open or exists. if (!readFile) { fputs("Unable to open file %s", stderr); } /* Here reading file and store into variable. */ int chCnt = 0; while ((readChar = getc(readFile)) != EOF) { result ^= (short) (readChar); for (intInnerLoopIndex = 0; intInnerLoopIndex > 1; //Perform bit shifting. result = result ^ 0xa001; //Perform XOR operation on result. } else { result = result >> 1; //Perform bit shifting. } } //content[chCnt] = readChar; chCnt++; } printf("CRC data length in file: %d", chCnt); return (result); } 

char readChar; 是错的,它需要是int readChar ;

getc ()返回一个int,因此它可以向你发出EOF信号。 EOF可能是值-1

如果将返回值转换为char,并读取值为255的字节,则255将被解释为-1,并且您将停止读取值为255的第一个字节。

这段代码在不同的方面是错误的:

  if (!readFile) { fputs("Unable to open file %s", stderr); } 

如果文件打开失败,你不会返回但继续! 而且put也是错误的,你没有指定文件名。

此外, getc()返回一个整数,但是你把它放在一个char中,它可能会在找到一个EOF字符时结束! 不要忽略编译器警告……

我会下载一个小的CRC计算器程序,以便您可以测试您的代码是否正常工作。