-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.c
155 lines (144 loc) · 2.54 KB
/
tools.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#ifndef __MINGW32__
#include <glob.h>
#endif
#include <zlib.h>
#include "tools.h"
uint8_t *load_file(const char *filename, size_t *size_out) {
FILE *f = fopen(filename, "rb");
if(!f) {
fprintf(
stderr,
"Could not open %s: %s (%d)\n",
filename,
strerror(errno),
errno
);
return NULL;
}
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
uint8_t *data = malloc(size);
if(!data) {
fprintf(
stderr,
"Could not allocate %lu bytes for %s: %s (%d)\n",
size, filename, strerror(errno), errno
);
fclose(f);
return NULL;
}
rewind(f);
fread(data, 1, size, f);
fclose(f);
if(size_out) *size_out = size;
return data;
}
uint8_t *load_gzfile(const char *filename, size_t *size_out) {
gzFile f = gzopen(filename, "rb");
if(!f) {
fprintf(
stderr,
"Could not open %s: %s (%d)\n",
filename,
strerror(errno),
errno
);
return NULL;
}
uint8_t *data = malloc(1024);
if(!data) {
fprintf(
stderr,
"Could not allocate 1024 bytes for %s: %s (%d)\n",
filename, strerror(errno), errno
);
gzclose(f);
return NULL;
}
size_t size = 0;
while(1) {
int r = gzread(f, data + size, 1024);
if(r < 0) break;
size += r;
if(r == 1024) {
data = realloc(data, size + 1024);
if(!data) {
fprintf(
stderr,
"Could not reallocate from %lu bytes to %lu bytes for %s: %s (%d)\n",
(unsigned long)size, (unsigned long)size + 1024, filename, strerror(errno), errno
);
gzclose(f);
return NULL;
}
} else break;
}
gzclose(f);
if(size_out) *size_out = size;
return data;
}
int gcd(int a, int b) {
int c = a % b;
while(c > 0) {
a = b;
b = c;
c = a % b;
}
return b;
}
void csv_quote(char *str, size_t len) {
if(len == 0) len = strlen(str);
if(str == 0) {
putchar('\\');
putchar('N');
return;
}
putchar('"');
for(int i = 0; i < len; i++) {
switch(str[i]) {
case 0:
putchar('\\');
putchar(0);
break;
case '\\':
putchar('\\');
putchar('\\');
break;
case '\b':
putchar('\\');
putchar('b');
break;
case '\n':
putchar('\\');
putchar('n');
break;
case '\r':
putchar('\\');
putchar('r');
break;
case '\t':
putchar('\\');
putchar('t');
break;
case 26:
putchar('\\');
putchar('Z');
break;
case '"':
putchar('"');
putchar('"');
break;
default: putchar(str[i]);
}
}
putchar('"');
}