/* $Id: b64test2.c,v 1.4 2002/06/23 20:28:31 richdawe Exp $ */ /* * b64test2.c - Second test program for pakke's Base64 code * Copyright (C) 2000-2002 by Richard Dawe * * This test decodes the specified Base64 encoded file and writes the decoded * version to a specified file. It holds the whole of both files in memory. * It's crude, but it's just a test. */ #include #include #include #include #include #include "base64.h" /* -------- * - main - * -------- */ int main (int argc, char *argv[]) { FILE *fp_in = NULL; FILE *fp_out = NULL; struct stat s; void *in = NULL; char *c_in = NULL; void *out = NULL; size_t insize = 0; size_t outsize = 0; ssize_t ret = 0; char linebuf[80]; char *line = NULL; char *p = NULL; memset(&s, 0, sizeof(s)); if (argc < 3) { printf("Syntax: %s \n", argv[0]); return(EXIT_FAILURE); } fp_in = fopen(argv[1], "rt"); if (fp_in == NULL) { printf("Unable to open %s\n", argv[1]); return(EXIT_FAILURE); } fp_out = fopen(argv[2], "wb"); if (fp_out == NULL) { printf("Unable to open %s\n", argv[2]); return(EXIT_FAILURE); } if (fstat(fileno(fp_in), &s) != 0) { printf("Unable to fstat %s\n", argv[1]); return(EXIT_FAILURE); } /* Allocate a buffer to store the input file. */ in = malloc((size_t) s.st_size); if (in == NULL) { printf("Unable to allocate input buffer\n"); return(EXIT_FAILURE); } /* Now read line by line. Chop off the newlines at the end & spaces at * either end. This is so we end up with one big block of Base64 * text. */ c_in = (char *) in; while((line = fgets(linebuf, sizeof(linebuf), fp_in)) != NULL) { while(isspace(*line)) { line++; } for (p = line + strlen(line) - 1; isspace(*p); p--) { *p = '\0'; } strcpy(c_in, line); c_in += strlen(c_in); } fclose(fp_in); /* Now allocate the output buffer. */ insize = strlen((char *) in); ret = base64_get_decoded_size(in, insize); if (ret > 0) { outsize = (size_t) ret; } else { printf("Error obtaining size of decoded data\n"); return(EXIT_FAILURE); } out = malloc(outsize); if (out == NULL) { printf("Error allocating output buffer\n"); return(EXIT_FAILURE); } ret = base64_decode(in, insize, out, &outsize); if (ret < 0) { printf("Base64 decoding failed\n"); return(EXIT_FAILURE); } /* Now write the output file. */ fwrite(out, outsize, 1, fp_out); fclose(fp_out); return(EXIT_SUCCESS); }