diff options
author | Jakob Kaivo <jkk@ung.org> | 2019-08-01 09:29:36 -0400 |
---|---|---|
committer | Jakob Kaivo <jkk@ung.org> | 2019-08-01 09:29:36 -0400 |
commit | 3cdfc5819b7cdfb4007ed5150f78b5ab697cf583 (patch) | |
tree | 175ef7ed9aecd3dcb34ad1d57e707a430feaab4e | |
parent | 8ec89c5a53466a3d0689a406c0604cf9bdbe7640 (diff) |
initial commit
-rw-r--r-- | .gitignore | 2 | ||||
-rw-r--r-- | Makefile | 6 | ||||
-rw-r--r-- | array.c | 85 |
3 files changed, 93 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bd54761 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +array +*.o diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..4589eb4 --- /dev/null +++ b/Makefile @@ -0,0 +1,6 @@ +.POSIX: + +array: array.c + +clean: + rm *.o array @@ -0,0 +1,85 @@ +#define _POSIX_C_SOURCE 2 +#include <ctype.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +#define CHARS_PER_LINE 8 + +int make_array(const char *path, int include_size) +{ + FILE *f = stdin; + + if (path && strcmp(path, "-") != 0) { + f = fopen(path, "rb"); + if (f == NULL) { + perror(path); + return 1; + } + } else { + path = "stdin"; + } + + size_t plen = strlen(path); + char id[plen + 1]; + for (size_t i = 0; i < plen; i++) { + id[i] = isalnum(path[i]) ? path[i] : '_'; + } + id[plen] = '\0'; + + printf("unsigned char %s[] = {\n", id); + + int c; + int i = 0; + while ((c = fgetc(f)) != EOF) { + if (i == 0) { + putchar('\t'); + } + printf("0x%02hhx, ", c); + if (++i == CHARS_PER_LINE) { + putchar('\n'); + i = 0; + } + } + + if (i != 0) { + putchar('\n'); + } + + printf("};\n"); + + if (include_size) { + printf("size_t %s_size = sizeof(%s);\n", id, id); + } + + if (f != stdin) { + fclose(f); + } + + return 0; +} + + +int main(int argc, char *argv[]) +{ + int include_size = 0; + int c; + + while ((c = getopt(argc, argv, "s")) != -1) { + switch (c) { + case 's': + include_size = 1; + break; + + default: + return 1; + } + } + + int ret = 0; + do { + ret |= make_array(argv[optind++], include_size); + } while (optind < argc); + + return ret; +} |