home *** CD-ROM | disk | FTP | other *** search
/ back2roots/padua / padua.7z / padua / uucp / sendbatches.lzh / src / bencode.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-12-14  |  1.5 KB  |  73 lines

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