summaryrefslogtreecommitdiff
path: root/bin2c.c
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--bin2c.c78
1 files changed, 78 insertions, 0 deletions
diff --git a/bin2c.c b/bin2c.c
new file mode 100644
index 0000000..3e6aaa2
--- /dev/null
+++ b/bin2c.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2024 dwlr <dweller@cabin.digital>
+ *
+ * BSD 3-Clause License (BSD-3-Clause)
+ * See LICENSE for details
+ */
+
+#define _XOPEN_SOURCE 500
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+
+
+int main(int argc, char** argv)
+{
+ int rc = 0;
+ int ret = EXIT_SUCCESS;
+ FILE* in = stdin;
+ FILE* out = stdout;
+ const char* name = "stdin";
+ char buffer[4096] = {0};
+ size_t got = 0;
+
+ if(argc == 2)
+ {
+ name = argv[1];
+ in = fopen(name, "r");
+ if(!in)
+ {
+ perror("fopen");
+ exit(EXIT_FAILURE);
+ }
+
+ rc = snprintf(buffer, sizeof(buffer) - 1, "%s.h", name);
+ if(rc < 0)
+ {
+ perror("snprintf");
+ exit(EXIT_FAILURE);
+ }
+
+ out = fopen(buffer, "w");
+ if(!out)
+ {
+ perror("fopen");
+ fclose(in);
+ exit(EXIT_FAILURE);
+ }
+
+ }
+ else if(argc > 2) fprintf(stderr, "warning: ignoring excess paramters\n");
+
+ for(;;)
+ {
+ size_t i;
+
+ got = fread(buffer, 1, sizeof(buffer), in);
+ rc = ferror(in);
+ if(rc)
+ {
+ perror("fread");
+ ret = EXIT_FAILURE;
+ goto end;
+ }
+
+ for(i = 0; i < got; i++) fprintf(out, "'\\x%02x',", (unsigned char)buffer[i]);
+
+ rc = feof(in);
+ if(rc) break;
+ }
+
+ fprintf(out, "\n");
+
+end:
+ fclose(in);
+ fclose(out);
+ return ret;
+}