home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume7 / uuencode / uuencode.c < prev   
C/C++ Source or Header  |  1986-11-30  |  2KB  |  106 lines

  1. /*
  2.  * uuencode [input] output
  3.  *
  4.  * Encode a file so it can be mailed to a remote system.
  5.  */
  6. #include <stdio.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9.  
  10. /* ENC is the basic 1 character encoding function to make a char printing */
  11. #define ENC(c) (((c) & 077) + ' ')
  12.  
  13. main(argc, argv)
  14. char **argv;
  15. {
  16.     FILE *in;
  17.     struct stat sbuf;
  18.     int mode;
  19.  
  20.     /* optional 1st argument */
  21.     if (argc > 2) {
  22.         if ((in = fopen(argv[1], "r")) == NULL) {
  23.             perror(argv[1]);
  24.             exit(1);
  25.         }
  26.         argv++; argc--;
  27.     } else
  28.         in = stdin;
  29.  
  30.     if (argc != 2) {
  31.         printf("Usage: uuencode [infile] remotefile\n");
  32.         exit(2);
  33.     }
  34.  
  35.     /* figure out the input file mode */
  36.     fstat(fileno(in), &sbuf);
  37.     mode = sbuf.st_mode & 0777;
  38.     printf("begin %o %s\n", mode, argv[1]);
  39.  
  40.     encode(in, stdout);
  41.  
  42.     printf("end\n");
  43.     exit(0);
  44. }
  45.  
  46. /*
  47.  * copy from in to out, encoding as you go along.
  48.  */
  49. encode(in, out)
  50. FILE *in;
  51. FILE *out;
  52. {
  53.     char buf[80];
  54.     int i, n;
  55.  
  56.     for (;;) {
  57.         /* 1 (up to) 45 character line */
  58.         n = fr(in, buf, 45);
  59.         putc(ENC(n), out);
  60.  
  61.         for (i=0; i<n; i += 3)
  62.             outdec(&buf[i], out);
  63.  
  64.         putc('\n', out);
  65.         if (n <= 0)
  66.             break;
  67.     }
  68. }
  69.  
  70. /*
  71.  * output one group of 3 bytes, pointed at by p, on file f.
  72.  */
  73. outdec(p, f)
  74. char *p;
  75. FILE *f;
  76. {
  77.     int c1, c2, c3, c4;
  78.  
  79.     c1 = *p >> 2;
  80.     c2 = (*p << 4) & 060 | (p[1] >> 4) & 017;
  81.     c3 = (p[1] << 2) & 074 | (p[2] >> 6) & 03;
  82.     c4 = p[2] & 077;
  83.     putc(ENC(c1), f);
  84.     putc(ENC(c2), f);
  85.     putc(ENC(c3), f);
  86.     putc(ENC(c4), f);
  87. }
  88.  
  89. /* fr: like read but stdio */
  90. int
  91. fr(fd, buf, cnt)
  92. FILE *fd;
  93. char *buf;
  94. int cnt;
  95. {
  96.     int c, i;
  97.  
  98.     for (i=0; i<cnt; i++) {
  99.         c = getc(fd);
  100.         if (c == EOF)
  101.             return(i);
  102.         buf[i] = c;
  103.     }
  104.     return (cnt);
  105. }
  106.