Debian Codegraph @

util1/csd_util/base64.c

raw
1
2 /* Base64 encoder utility - written by Istvan Varga, Jan 2003 */
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <errno.h>
8
9 static const char *encode_table =
10 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
11
12 static int linepos = 0;
13 int maxlinepos = 72; /* max line width */
14 static int bitcnt = 0, inval = 0;
15 static FILE *infile = NULL;
16
17 /* convert 6 bits of input and write to output file */
18
19 int encode_byte(FILE *infl, FILE *outfl)
20 {
21 int c;
22
23 if (bitcnt < 0) return 0; /* end of file */
24 if (bitcnt < 6) { /* read next byte from input file */
25 c = getc(infl);
26 if (c != EOF) {
27 bitcnt += 8;
28 inval |= ((c & 0xFF) << (24 - bitcnt));
29 }
30 }
31 if (bitcnt == 0) return 0; /* end of file */
32 if (!(linepos % maxlinepos))
33 putc('\n', outfl); /* wrap line */
34 linepos++;
35 /* convert left 6 bits */
36 putc((int) encode_table[((inval & 0x00FC0000) >> 18)], outfl);
37 inval = (inval << 6) & 0x00FFFFC0;
38 bitcnt -= 6;
39 return 1;
40 }
41
42 /* convert an entire input file */
43
44 void encode_file(char *inflname, FILE *outfl, int style)
45 {
46 char *s, *s0;
47
48 s0 = inflname;
49 s = s0 + (int) strlen(s0);
50 /* remove any leading components from filename */
51 do {
52 s--;
53 } while (s >= s0 && *s != '/' && *s != '\\' && *s != ':');
54 s++;
55 if (strlen(s) < 1) {
56 fprintf(stderr, "csb64enc: \"%s\": invalid input file name\n", s0);
57 exit(-1);
58 }
59 /* open file */
60 infile = fopen(s0, "rb");
61 if (infile == NULL) {
62 fprintf(stderr, "csb64enc: error opening input file %s: %s\n",
63 s0, strerror(errno));
64 exit(-1);
65 }
66 /* create new CSD tag and encode file */
67 if (style==1)
68 fprintf(outfl, "<CsMidifileB>");
69 else if (style==2)
70 fprintf(outfl, "<CsFileC filename=\"%s\">", s);
71 else
72 fprintf(outfl, "<CsFileB filename=\"%s\">", s);
73 linepos = bitcnt = inval = 0;
74 while (encode_byte(infile, outfl));
75 if (style)
76 fprintf(outfl, "\b</CsMidifileB>\n");
77 else
78 fprintf(outfl, "\n</CsFileB>\n");
79 /* close file */
80 fclose(infile); infile = NULL;
81 }