Hi,
Need to know how to do a CRC on a file ?.
I need the code in C++ or C or in VB.
Any help is appreciated..
Thanks,
Pradeep
Printable View
Hi,
Need to know how to do a CRC on a file ?.
I need the code in C++ or C or in VB.
Any help is appreciated..
Thanks,
Pradeep
First off -
There is no one CRC algorithm - they are 16 bit or 32 bit.
Then a polynomial is applied (mask). There are a lot of polynomials used
As long as you use the same CRC32 and the same polynomial, results for identical data streams match. If not, all bets are off.
Attached is a CRC written in VB
A more robust C implementation
Code:/* crc-32 for files using autodin II, NIC polynomial 04/16/2002 4:33AM jmc*/
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#define U_LONG unsigned int
#define U_CHAR unsigned char
#define CRC32_POLY 0x04c11db7 /* AUTODIN II, Ethernet, & FDDI */
static U_LONG crc32_table[256];
static struct stat a;
void init_crc32(void);
void test(FILE *);
U_LONG crc32(U_CHAR*,int);
int main(int argc,char *argv[]){
FILE *in;
char *buf;
if (stat(argv[1],&a)) {
printf("Cannot stat %s\n",argv[1]);
perror("Usage: crc32 <filename> \nError:");
exit(EXIT_FAILURE);
}
test(in=fopen(argv[1],"rb") );
buf=(char*)malloc(a.st_size);
fread(buf,1,a.st_size,in);
fclose(in);
init_crc32(); /* build table */
printf("%X\n", crc32((U_CHAR*)buf,a.st_size));
free(buf);
return 0;
}
U_LONG crc32(U_CHAR *buf, int len)
{
U_CHAR *p;
U_LONG crc;
crc = 0xffffffff; /* preload shift register, per CRC-32 spec */
for (p = buf; len > 0; ++p, --len)
crc = (crc << 8) ^ crc32_table[(crc >> 24) ^ *p];
return ~crc; /* transmit complement, per CRC-32 spec */
}
/*
* Build auxiliary table for parallel byte-at-a-time CRC-32.
*/
void init_crc32()
{
int i, j;
U_LONG c;
for (i = 0; i < 256; ++i) {
for (c = i << 24, j = 8; j > 0; --j)
c = c & 0x80000000 ? (c << 1) ^ CRC32_POLY : (c << 1);
crc32_table[i] = c;
}
}
/* validate file open, exit on bad file */
void test(FILE *tst){
if(tst==NULL) {
perror("Error opening input file:");
exit(EXIT_FAILURE);
}
}
Hae,
Thanks a Lot..
The C code always return's 0 on any file.. But the VB one works fine.. Could you please check the C version ..
Thanks,
Pradeep
Woww.... its working fine now...
I forgot to copy stat.. and hence.....
Hae Thanks a Lot...
Pradeep
Returning zero means it succeeded, in unix terms and in standard ANSI C terms as well.
Plus, that code has been in production for a long time - I don't think there's too much wrong with it.
All the code does is print the CRC.
Thanks Jim
You can also use MD5 Hash for checking the authenticity of the file.