Advertisement
Guest User

Untitled

a guest
Dec 9th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1.  
  2. #include <stdio.h>
  3. #include <stdlib.h> // For exit()
  4. #include <string.h>
  5. #include <ctype.h>
  6. #include <assert.h>
  7.  
  8. void compress_file(FILE *fp_in, FILE *fp_out);
  9. void uncompress_file(FILE *fp_in, FILE *fp_out);
  10.  
  11. int main(int argc, char **argv) {
  12.     assert(argc >= 3 && "my-zip: [input files] 'out put file'\n");
  13.  
  14.     FILE *fptr_w;
  15.     char file_r[100], file_w[100];
  16.     // Last argv is target file
  17.     strcpy(file_w, argv[argc - 1]);
  18.  
  19.     fptr_w = fopen(file_w, "w");
  20.     if (fptr_w == NULL) {
  21.         printf("Cannot open file %s \n", file_w);
  22.         exit(1);
  23.     }
  24.  
  25.     for (int i = 1; i < argc - 1; i++) {
  26.         // Open file for reading
  27.         FILE *fptr_r;
  28.         strcpy(file_r, argv[i]);
  29.         fptr_r = fopen(file_r, "r");
  30.         if (fptr_r == NULL) {
  31.             printf("Cannot open file %s \n", file_r);
  32.             exit(1);
  33.         } else {
  34.             printf("compressing file %s\n", file_r);
  35.             compress_file(fptr_r, fptr_w);
  36.             fclose(fptr_r);
  37.         }
  38.     }
  39.  
  40.     /*
  41.     size_t bytes;
  42.     while (0 < (bytes = fread(buffer, 1, sizeof(buffer), fptr1))) {
  43.         strcpy(buffer, compress(buffer));
  44.         fwrite(buffer, 1, bytes, fptr2);
  45.     }
  46.    
  47.     c = fgetc(fptr1);
  48.     while (c != EOF)
  49.     {
  50.         fputc(c, fptr2);
  51.         c = fgetc(fptr1);
  52.     }
  53.     */
  54.  
  55.     fclose(fptr_w);
  56.     return 0;
  57. }
  58.  
  59. void compress_file(FILE *fp_in, FILE *fp_out) {
  60.     int count, ch, ch2, chk;
  61.  
  62.         ch = getc(fp_in);
  63.         ch2 = ch;
  64.         while (ch2 != EOF) {
  65.             // if next byte is the same increase count and test
  66.             for (count = 0; ch2 == ch && count < 255; count++) {
  67.                 ch2 = getc(fp_in); // set next variable for comparison
  68.             }
  69.             // write bytes into new file
  70.             putc(count, fp_out);
  71.             putc(ch, fp_out);
  72.             ch = ch2;
  73.         }
  74. }
  75.  
  76. void uncompress_file(FILE *fp_in, FILE *fp_out) {
  77.     int count, ch, ch2;
  78.  
  79.     for (count = 0; ch2 != EOF; count = 0) {
  80.         ch = getc(fp_in);   // grab first byte
  81.         ch2 = getc(fp_in);  // grab second byte
  82.         // write the bytes
  83.         do {
  84.             putc(ch2, fp_out);
  85.             count++;
  86.         } while (count < ch);
  87.     }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement