-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhx.c
48 lines (43 loc) · 1.07 KB
/
hx.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
/* Convert a text file consisting of 64-bit hex numbers into a binary file
* Author: Richard James Howe
* License: Public Domain
* Repository: https//github.com/howerj/os */
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static FILE *fopen_or_die(const char *file, const char *mode) {
assert(file);
assert(mode);
errno = 0;
FILE *f = fopen(file, mode);
if (!f) {
(void)fprintf(stderr, "Could not open file '%s' in mode '%s': %s\n", file, mode, strerror(errno));
exit(1);
}
return f;
}
int main(int argc, char **argv) {
int r = 0;
if (argc != 3) {
(void)fprintf(stderr, "usage: %s in.hex out.bin\n", argv[0]);
return 1;
}
FILE *in = fopen_or_die(argv[1], "rb"), *out = fopen_or_die(argv[2], "wb");
uint64_t u = 0;
while (fscanf(in, "%"SCNx64, &u) == 1) {
errno = 0;
if (1 != fwrite(&u, sizeof u, 1, out)) {
(void)fprintf(stderr, "unable to write word: %s\n", strerror(errno));
return 1;
}
}
if (fclose(in) < 0)
r = 1;
if (fclose(out) < 0)
r = 1;
return r;
}