-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcrc32.c
68 lines (54 loc) · 1.5 KB
/
crc32.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <crc32.h>
#include <zlib.h>
int CRC32FromFile(FILE *file, long from, long to, unsigned long *crc)
{
if(from >= to)
{
fprintf(stderr, "Invalid span of data for CRC: from = %li; to = %li!\n", from, to);
return -1;
}
// Create Buffer
unsigned char *buffer;
size_t buffersize = to-from;
buffer = malloc(buffersize * sizeof(unsigned char));
if(buffer == NULL)
{
fprintf(stderr, "%s, %i: ", __FILE__, __LINE__);
fprintf(stderr, "Fatal Error! - malloc returned NULL!\n");
return -1;
}
// Go to begin of relevant data
int error;
error = fseek(file, from, SEEK_SET);
if(error != 0)
{
fprintf(stderr, "%s, %i: ", __FILE__, __LINE__);
fprintf(stderr, "Fatal Error! - Setting correct file position failed!\n");
free(buffer);
return -1;
}
// Read File
size_t bytesread;
bytesread = fread(buffer, 1, buffersize, file);
if(bytesread != buffersize)
{
fprintf(stderr, "%s, %i: ", __FILE__, __LINE__);
fprintf(stderr, "Fatal Error! - Only %zu of %zu bytes read from file!\n", bytesread, buffersize);
free(buffer);
return -1;
}
// Calculate CRC32
if(crc == NULL)
{
free(buffer);
return 0;
}
*crc = crc32(0x00000000, buffer, buffersize);
// Clean up
free(buffer);
return 0;
}
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4