home *** CD-ROM | disk | FTP | other *** search
/ Unix System Administration Handbook 1997 October / usah_oct97.iso / news / cnews.tar / batch / bencode.c < prev    next >
C/C++ Source or Header  |  1991-11-04  |  1KB  |  68 lines

  1. /*
  2.  * bencode [file]
  3.  */
  4. #include <stdio.h>
  5. #include "coder.h"
  6. #define MAXPERLINE 78        /* max chars/line */
  7. char *myname;
  8.  
  9. main(argc,argv) 
  10.     char **argv;
  11. {
  12.     register FILE *fin = stdin, *fout = stdout; /* faster in a register */
  13.     register int c, bcount, ccount = MAXPERLINE-1;
  14.     register long word, nbytes;
  15.     register unsigned crc;
  16.  
  17.     myname = argv[0];
  18.     if (sizeof(word) < 4)
  19.         fprintf(stderr, "%s: word size too small\n", myname), exit(1);
  20.     if (argc == 2 && (fin = fopen(argv[1], "r")) == NULL) {
  21.         fprintf(stderr, "%s: ", myname);
  22.         perror(argv[1]);
  23.         exit(1);
  24.     }
  25.     else if (argc > 2) {
  26.         fprintf(stderr, "Usage: %s [file]\n", myname);
  27.         exit(1);
  28.     }
  29.  
  30. #define PUTC(c) \
  31.     putc(c, fout); \
  32.     if (--ccount == 0) { \
  33.         putc('\n', fout); \
  34.         ccount = MAXPERLINE-1; \
  35.     }
  36.  
  37.     fputs(header, fout);
  38.     word = 0;
  39.     bcount = 3;
  40.     crc = 0;
  41.     for (nbytes = 0; (c = getc(fin)) != EOF; nbytes++) {
  42.         CRC(crc, c);
  43.         word <<= 8;
  44.         word |= c;
  45.         if (--bcount == 0) {
  46.             PUTC(ENCODE((word >> 18) & 077));
  47.             PUTC(ENCODE((word >> 12) & 077));
  48.             PUTC(ENCODE((word >>  6) & 077));
  49.             PUTC(ENCODE((word      ) & 077));
  50.             word = 0;
  51.             bcount = 3;
  52.         }
  53.     }
  54.     /*
  55.      * A trailing / marks end of data.
  56.      * The last partial encoded word follows in hex,
  57.      * preceded by a byte count.
  58.      */
  59.     if (ccount != MAXPERLINE-1)    /* avoid empty lines */
  60.         putc('\n', fout);
  61.     fprintf(fout, "/%d%x\n", 3-bcount, word);
  62.     /*
  63.      * And finally the byte count and CRC.
  64.      */
  65.     fprintf(fout, "%ld %x\n", nbytes, crc & 0xffff);
  66.     exit(0);
  67. }
  68.