diff options
Diffstat (limited to 'bin2c.c')
-rw-r--r-- | bin2c.c | 78 |
1 files changed, 78 insertions, 0 deletions
@@ -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; +} |