simple_compression.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #include <stdio.h> // printf
  11. #include <stdlib.h> // free
  12. #include <string.h> // strlen, strcat, memset
  13. #include <zstd.h> // presumes zstd library is installed
  14. #include "common.h" // Helper functions, CHECK(), and CHECK_ZSTD()
  15. static void compress_orDie(const char* fname, const char* oname)
  16. {
  17. size_t fSize;
  18. void* const fBuff = mallocAndLoadFile_orDie(fname, &fSize);
  19. size_t const cBuffSize = ZSTD_compressBound(fSize);
  20. void* const cBuff = malloc_orDie(cBuffSize);
  21. /* Compress.
  22. * If you are doing many compressions, you may want to reuse the context.
  23. * See the multiple_simple_compression.c example.
  24. */
  25. size_t const cSize = ZSTD_compress(cBuff, cBuffSize, fBuff, fSize, 1);
  26. CHECK_ZSTD(cSize);
  27. saveFile_orDie(oname, cBuff, cSize);
  28. /* success */
  29. printf("%25s : %6u -> %7u - %s \n", fname, (unsigned)fSize, (unsigned)cSize, oname);
  30. free(fBuff);
  31. free(cBuff);
  32. }
  33. static char* createOutFilename_orDie(const char* filename)
  34. {
  35. size_t const inL = strlen(filename);
  36. size_t const outL = inL + 5;
  37. void* const outSpace = malloc_orDie(outL);
  38. memset(outSpace, 0, outL);
  39. strcat(outSpace, filename);
  40. strcat(outSpace, ".zst");
  41. return (char*)outSpace;
  42. }
  43. int main(int argc, const char** argv)
  44. {
  45. const char* const exeName = argv[0];
  46. if (argc!=2) {
  47. printf("wrong arguments\n");
  48. printf("usage:\n");
  49. printf("%s FILE\n", exeName);
  50. return 1;
  51. }
  52. const char* const inFilename = argv[1];
  53. char* const outFilename = createOutFilename_orDie(inFilename);
  54. compress_orDie(inFilename, outFilename);
  55. free(outFilename);
  56. return 0;
  57. }