morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base.git
Log | Files | Refs

uuencode.c (1580B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <sys/stat.h>
      5 #include <sys/types.h>
      6 #include <unistd.h>
      7 
      8 #include "util.h"
      9 
     10 static void uuencode(FILE *, const char *, const char *);
     11 
     12 static void
     13 usage(void)
     14 {
     15 	eprintf("usage: %s [file] name\n", argv0);
     16 }
     17 
     18 int
     19 main(int argc, char *argv[])
     20 {
     21 	FILE *fp;
     22 
     23 	ARGBEGIN {
     24 	case 'm':
     25 		eprintf("-m not implemented\n");
     26 	default:
     27 		usage();
     28 	} ARGEND;
     29 
     30 	if (argc == 0 || argc > 2)
     31 		usage();
     32 
     33 	if (argc == 1) {
     34 		uuencode(stdin, argv[0], "<stdin>");
     35 	} else {
     36 		if (!(fp = fopen(argv[0], "r")))
     37 			eprintf("fopen %s:", argv[0]);
     38 		uuencode(fp, argv[1], argv[0]);
     39 		fclose(fp);
     40 	}
     41 	return 0;
     42 }
     43 
     44 static void
     45 uuencode(FILE *fp, const char *name, const char *s)
     46 {
     47 	struct stat st;
     48 	unsigned char buf[45], *p;
     49 	ssize_t n;
     50 	int ch;
     51 
     52 	if (fstat(fileno(fp), &st) < 0)
     53 		eprintf("fstat %s:", s);
     54 	printf("begin %o %s\n", st.st_mode & 0777, name);
     55 	while ((n = fread(buf, 1, sizeof(buf), fp))) {
     56 		ch = ' ' + (n & 0x3f);
     57 		putchar(ch == ' ' ? '`' : ch);
     58 		for (p = buf; n > 0; n -= 3, p += 3) {
     59 			if (n < 3) {
     60 				p[2] = '\0';
     61 				if (n < 2)
     62 					p[1] = '\0';
     63 			}
     64 			ch = ' ' + ((p[0] >> 2) & 0x3f);
     65 			putchar(ch == ' ' ? '`' : ch);
     66 			ch = ' ' + (((p[0] << 4) | ((p[1] >> 4) & 0xf)) & 0x3f);
     67 			putchar(ch == ' ' ? '`' : ch);
     68 			ch = ' ' + (((p[1] << 2) | ((p[2] >> 6) & 0x3)) & 0x3f);
     69 			putchar(ch == ' ' ? '`' : ch);
     70 			ch = ' ' + (p[2] & 0x3f);
     71 			putchar(ch == ' ' ? '`' : ch);
     72 		}
     73 		putchar('\n');
     74 	}
     75 	if (ferror(fp))
     76 		eprintf("'%s' read error:", s);
     77 	printf("%c\nend\n", '`');
     78 }