From 221a8588c0080978c716f42d8191e6738ab9e99f Mon Sep 17 00:00:00 2001 From: Eric Date: Mon, 26 May 2025 22:38:33 +0200 Subject: [PATCH] add writing to file output option --- main.c | 37 ++++++++++++++++--------------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/main.c b/main.c index a0cbc32..77dd98a 100644 --- a/main.c +++ b/main.c @@ -14,7 +14,7 @@ main(int argc, char *argv[]) { int c, n, dec, hlp; char *prog = *argv; - FILE *fp; + FILE *in, *out; dec = hlp = 0; while (--argc > 0 && (*++argv)[0] == '-') @@ -32,36 +32,31 @@ main(int argc, char *argv[]) break; } if (hlp) { - fprintf(stdout, "Usage: %s -d -h file\n", prog); - } else if (argc != 1) { - if (dec) { - while ((n = getsxts(stdin, sbuf, SBUFSIZE))) { - n = decode(sbuf, n, obuf); - fwrite(obuf, sizeof(*obuf), n, stdout); - } - } else { - while ((n = getocts(stdin, obuf, OBUFSIZE))) { - encode(obuf, n, sbuf); - printf("%s", sbuf); - } - } + fprintf(stdout, "Usage: %s -d -h infile outfile\n", prog); } else { - if ((fp = fopen(*argv, "r")) == NULL) { + if (argc >= 1 && (in = fopen(*argv, "r")) == NULL) { fprintf(stderr, "%s: can't open %s\n", prog, *argv); exit(EXIT_FAILURE); } - else if (dec) { - while ((n = getsxts(fp, sbuf, SBUFSIZE))) { + if (argc == 2 && (out = fopen(*(argv+1), "w")) == NULL) { + fprintf(stderr, "%s: can't open %s\n", prog, *(argv+1)); + exit(EXIT_FAILURE); + } + if (dec) { + while ((n = getsxts((argc >= 1) ? in : stdin, sbuf, SBUFSIZE))) { n = decode(sbuf, n, obuf); - fwrite(obuf, sizeof(*obuf), n, stdout); + fwrite(obuf, sizeof(*obuf), n, (argc == 2) ? out : stdout); } } else { - while ((n = getocts(fp, obuf, OBUFSIZE))) { + while ((n = getocts((argc >= 1) ? in : stdin, obuf, OBUFSIZE))) { encode(obuf, n, sbuf); - printf("%s", sbuf); + fprintf((argc == 2) ? out : stdout, "%s", sbuf); } } - fclose(fp); + if (in) + fclose(in); + if (out) + fclose(out); } exit(EXIT_SUCCESS); }