Advertisement
aaaaaa123456789

xorfiles

Oct 17th, 2014
319
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdint.h>
  5.  
  6. void compute_xor(FILE *, FILE **, unsigned);
  7. inline void xor(void *, const void *, unsigned);
  8.  
  9. int main (int argc, char ** argv) {
  10.   if (argc < 3) {
  11.     fprintf(stderr, "usage: %s outfile infile1 [infile2 [infile3 [... ]]]\n", *argv);
  12.     return 1;
  13.   }
  14.   FILE ** infiles = malloc(sizeof(FILE *) * (argc - 2));
  15.   int fileno;
  16.   for (fileno = 0; fileno < (argc - 2); fileno ++) {
  17.     infiles[fileno] = fopen(argv[fileno + 2], "rb");
  18.     if (!infiles[fileno]) {
  19.       fprintf(stderr, "%s: could not open file %s for reading\n", *argv, argv[fileno + 2]);
  20.       for (fileno --; fileno >= 0; fileno --) fclose(infiles[fileno]);
  21.       return 2;
  22.     }
  23.   }
  24.   FILE * outfile = fopen(argv[1], "wb");
  25.   if (!outfile) {
  26.     fprintf(stderr, "%s: could not open file %s for writing\n", *argv, argv[1]);
  27.     for (fileno --; fileno >= 0; fileno --) fclose(infiles[fileno]);
  28.     return 2;
  29.   }
  30.   compute_xor(outfile, infiles, fileno);
  31.   free(infiles);
  32.   return 0;
  33. }
  34.  
  35. void compute_xor (FILE * out, FILE ** in, unsigned count) {
  36.   unsigned buffer_size = 2 << 20;
  37.   char * buffer = NULL;
  38.   while (!buffer) {
  39.     buffer = malloc(buffer_size);
  40.     buffer_size >>= 1;
  41.     if (!buffer_size) abort();
  42.   }
  43.   unsigned last_read, current_file;
  44.   int rv;
  45.   while (1) {
  46.     memset(buffer, 0, buffer_size);
  47.     last_read = 0;
  48.     for (current_file = 0; current_file < count; current_file ++) {
  49.       if (!in[current_file]) continue;
  50.       rv = fread(buffer + buffer_size, 1, buffer_size, in[current_file]);
  51.       if (rv < buffer_size) {
  52.         fclose(in[current_file]);
  53.         in[current_file] = NULL;
  54.       }
  55.       if (rv) xor(buffer, buffer + buffer_size, rv);
  56.       if (rv > last_read) last_read = rv;
  57.     }
  58.     if (!last_read) break;
  59.     fwrite(buffer, 1, last_read, out);
  60.   }
  61.   fclose(out);
  62.   free(buffer);
  63. }
  64.  
  65. inline void xor (void * destination, const void * source, unsigned length) {
  66.   uint_fast8_t * dstfast = destination;
  67.   const uint_fast8_t * srcfast = source;
  68.   while (length > sizeof(uint_fast8_t)) {
  69.     *(dstfast ++) ^= *(srcfast ++);
  70.     length -= sizeof(uint_fast8_t);
  71.   }
  72.   unsigned char * dstbyte = (unsigned char *) dstfast;
  73.   const unsigned char * srcbyte = (const unsigned char *) srcfast;
  74.   while (length) {
  75.     *(dstbyte ++) ^= *(srcbyte ++);
  76.     length --;
  77.   }
  78. }
Advertisement
RAW Paste Data Copied
Advertisement