Helper Code Used In Examples
This section contains helper code that makes examples easier to use. Users are free to use this code in their project if it is helpful.
read_file
The following C function reads an entire file into memory. This may be used to load the license file.
1 void* read_file(char const* filename, size_t* size)
2 {
3 FILE* f = NULL;
4 int r = 0;
5 long filesize = 0;
6 unsigned long readbytes = 0;
7 void* result = NULL;
8
9 if (!filename || !size) {
10 errno = EINVAL;
11 return NULL;
12 }
13
14 f = fopen(filename, "rb");
15 if (!f)
16 return NULL;
17
18 r = fseek(f, 0, SEEK_END);
19 if (r < 0) {
20 int error = errno;
21 fclose(f);
22 errno = error;
23 return NULL;
24 }
25
26 filesize = ftell(f);
27 if (filesize < 0) {
28 int error = errno;
29 fclose(f);
30 errno = error;
31 return NULL;
32 }
33
34 r = fseek(f, 0, SEEK_SET);
35 if (r < 0) {
36 int error = errno;
37 fclose(f);
38 errno = error;
39 return NULL;
40 }
41
42 result = malloc((size_t) filesize);
43 if (!result) {
44 int error = errno;
45 fclose(f);
46 errno = error;
47 return NULL;
48 }
49
50 readbytes = fread(result, 1, (size_t) filesize, f);
51 fclose(f);
52
53 if ((long) readbytes < filesize)
54 result = realloc(result, (size_t) readbytes);
55
56 if (result)
57 *size = (size_t) readbytes;
58 return result;
59 }