compdecomp.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * :make compdecomp CFLAGS=-Wall LDFLAGS=-lz
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <zlib.h>
  7. #define MEM_LIMIT (128*1024*1024)
  8. int main(int argc, char *argv[])
  9. {
  10. void *pi, *po = NULL;
  11. FILE *fi, *fo;
  12. int ret, si, so;
  13. if (argc != 4)
  14. {
  15. printf("usage: %s <0|1> <infile> <outfile>\n", argv[0]);
  16. return 1;
  17. }
  18. fi = fopen(argv[2], "rb");
  19. if (fi == NULL) return 2;
  20. fseek(fi, 0, SEEK_END);
  21. si = ftell(fi);
  22. fseek(fi, 0, SEEK_SET);
  23. pi = malloc(si);
  24. if (pi == NULL) return 3;
  25. fread(pi, 1, si, fi);
  26. fclose(fi);
  27. if (atoi(argv[1]))
  28. {
  29. // decompress
  30. so = si;
  31. do
  32. {
  33. so *= 16;
  34. if (so > MEM_LIMIT) return 4;
  35. po = realloc(po, so);
  36. if (po == NULL) return 5;
  37. ret = uncompress(po, (uLongf *) &so, pi, si);
  38. }
  39. while (ret == Z_BUF_ERROR);
  40. }
  41. else
  42. {
  43. // compress
  44. so = si + 1024;
  45. po = malloc(so);
  46. if (po == NULL) return 5;
  47. ret = compress2(po, (uLongf *) &so, pi, si, Z_BEST_COMPRESSION);
  48. }
  49. if (ret == Z_OK)
  50. {
  51. fo = fopen(argv[3], "wb");
  52. if (fo == NULL) return 6;
  53. fwrite(po, 1, so, fo);
  54. fclose(fo);
  55. }
  56. printf("result %i, size %i -> %i\n", ret, si, so);
  57. return ret;
  58. }