Advertisement
Guest User

Untitled

a guest
Aug 16th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. inline int Extract_file(FileEntryHeader * fh, FILE * f, HuffmanTree * ht)
  2. {
  3.     unsigned char * buff = calloc(read_buff_size, sizeof(unsigned char));
  4.     uint32_t checksum= 0;
  5.     register unsigned int i, poz = 0, l = 0, node = ht->root, bw = 0;
  6.     i = 0;
  7.     FILE * out = fopen(fh->file_name, "wb");
  8.     if (out == NULL)
  9.     {
  10.         //Just in case we can't open the file for writing
  11.         free(buff);
  12.         return -1;
  13.     }
  14.     //bw means bytes written, it is used to check when the file was written
  15.     while ( bw < fh->file_size)
  16.     {
  17.         if (poz == l*8)
  18.         {
  19.             i+=l;
  20.             l = fread(buff, sizeof(unsigned char), min(read_buff_size, fh->bytes_n-i), f);
  21.             poz = 0;
  22.             debug("Just read %d bytes, i=%d, bytes_n is %d\n", l, i, fh->bytes_n);
  23.         }
  24.  
  25.         if (ht->nodes[node].right == -1 && ht->nodes[node].left == -1)
  26.         {
  27.             //This means that we can write the value into the file
  28.             fwrite(&(ht->nodes[node].value), sizeof(uint8_t), 1, out);
  29.             checksum += ht->nodes[node].value;
  30.             node = ht->root;
  31.             ++bw;
  32.         }
  33.         //Reading the current bit
  34.         if (buff[poz/8] & (1<<(7-poz%8)))
  35.             node = ht->nodes[node].right;
  36.         else
  37.             node = ht->nodes[node].left;
  38.         //Jumping to the new position
  39.         ++poz;
  40.     }
  41.     //Cleanup
  42.     fclose(out);
  43.     free(buff);
  44.     //If the checksum aint' good
  45.     if (checksum != fh->checksum)
  46.     {
  47.         fprintf(stderr, "File %s is CORRUPT\n", fh->file_name);
  48.         unlink(fh->file_name);
  49.         debug("Checksum is %d it should be %d\n", checksum , fh->checksum);
  50.     }
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement