-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtools.c
76 lines (66 loc) · 1.99 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
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
// http://stackoverflow.com/a/1921557
typedef enum { false, true } bool;
void error(int code, char message[]) {
fprintf(stderr, "Error: ");
fputs(message, stderr);
fprintf(stderr, "\n");
exit(code);
}
void errorf(int code, char message[], char arg[]) {
fprintf(stderr, "Error: ");
fprintf(stderr, message, arg);
fprintf(stderr, "\n");
exit(code);
}
char * bytes_to_hex(unsigned char bytes[], int size) {
char *hex = malloc((size * 2) + 1);
if (hex == NULL) error(1, "Malloc failed!");
for (int i = 0; i < size; i++) {
sprintf(hex + (i * 2), "%02x", bytes[i]);
}
return hex;
}
FILE * create_file(char filename[]) {
// http://stackoverflow.com/a/230581
int fd = open(filename, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) errorf(1, "Could not write to %s", filename);
// http://stackoverflow.com/a/1941472
return fdopen(fd, "wb");
}
bool file_exists(char arg[]) {
// http://stackoverflow.com/a/230068
// Not perfect, because e.g. it won't allow the use of /dev/stdout
if (access(arg, F_OK) != -1) return true;
return false;
}
void read_key(char filename[], unsigned char key[], int key_size) {
FILE *f = fopen(filename, "rb");
if (fread(key, 1, key_size, f) != key_size)
errorf(1, "Could not read the key from <%s>", filename);
fclose(f);
}
struct content {
size_t size;
unsigned char *bytes;
};
typedef struct content Content;
Content read_file(char filename[]) {
FILE *f = fopen(filename, "rb");
Content c;
if (f == 0) errorf(1, "Could not read <%s>", filename);
fseek(f, 0, SEEK_END);
long size = ftell(f);
if (size < 0) errorf(1, "Could not read <%s>", filename);
c.size = (size_t)size;
fseek(f, 0, SEEK_SET);
c.bytes = malloc(c.size);
if (c.bytes == NULL) error(1, "Malloc failed!");
fread(c.bytes, c.size, 1, f);
fclose(f);
return c;
}