From 6c080c486f987ba30e7efe209f1310c6cfca0beb Mon Sep 17 00:00:00 2001 From: dweller Date: Wed, 31 Jul 2024 02:37:41 +0300 Subject: initial commit --- bin2c.c | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 bin2c.c (limited to 'bin2c.c') 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 + * + * BSD 3-Clause License (BSD-3-Clause) + * See LICENSE for details + */ + +#define _XOPEN_SOURCE 500 + +#include +#include +#include + + +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; +} -- cgit v1.2.3