Advertisement
xerpi

xorer by xerpi

Apr 8th, 2012
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.10 KB | None | 0 0
  1. /* by xerpi */
  2.  
  3. #include <stdio.h>
  4.  
  5. #define min(num1, num2) (num1<num2 ? num1 : num2)
  6. #define BUF_SIZE 1
  7.  
  8. int file_size(FILE *file);
  9. void xorer( FILE *input1,  FILE *input2,  FILE *output);
  10.  
  11. int main(int argc, char **argv){
  12.  
  13.     if( argc < 3 ){
  14.         printf("Too low arguments.\nUse: xorer <file1> <file2> (<output>)");
  15.         return -1;
  16.     }
  17.  
  18.     FILE *input1;
  19.     FILE *input2;
  20.     FILE *output;
  21.     char *output_filename;
  22.     //Check if the 4th argument exists, if it exists, it'll be the name of the output file
  23.         if( argc >= 4)
  24.             output_filename = argv[3];
  25.         else
  26.             output_filename = "xored";
  27.     //Open the files
  28.         input1 =  fopen (argv[1], "r");
  29.             if(!input1){
  30.                 printf("File %s could not be opened.", argv[1]);
  31.                 return -1;
  32.             }
  33.         input2 =  fopen (argv[2], "r");
  34.             if(!input2){
  35.                 printf("File %s could not be opened.", argv[2]);
  36.                 return -1;
  37.             }
  38.         output =  fopen (output_filename, "w+");
  39.     //Xor the files
  40.         xorer(input1, input2, output);
  41.     //Close the files
  42.         fclose(input1);
  43.         fclose(input2);
  44.         fflush(output);
  45.         fclose(output);
  46.     return 0;
  47. }
  48.  
  49.  
  50. int file_size(FILE *file){
  51.     fseek(file, 0, SEEK_END);
  52.     return ftell(file);
  53. }
  54.  
  55. void xorer( FILE *input1,  FILE *input2,  FILE *output){
  56.     int i, min_size, size1, size2;
  57.     unsigned char buffer, data1, data2;
  58.      //Check the file size
  59.         size1 = file_size(input1);
  60.         size2 = file_size(input2);
  61.      //Set the cursor at the begin of the files
  62.         fseek(input1, 0, SEEK_SET);
  63.         fseek(input2, 0, SEEK_SET);
  64.             min_size = min(size1, size2);
  65.             printf("Size file 1: %i\nSize file 2: %i\nOutput file size: %i", size1, size2, min_size);
  66.     //Xor algorithm
  67.         for(i = 0; i< min_size; i++){
  68.             fread(&data1, 1, BUF_SIZE, input1);
  69.             fread(&data2, 1, BUF_SIZE, input2);
  70.             buffer = data1 ^ data2;
  71.             fwrite(&buffer, 1, BUF_SIZE, output);
  72.         }
  73.     return;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement