Path: blob/main/sys/contrib/zstd/examples/simple_compression.c
48249 views
/*1* Copyright (c) Yann Collet, Facebook, Inc.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/910#include <stdio.h> // printf11#include <stdlib.h> // free12#include <string.h> // strlen, strcat, memset13#include <zstd.h> // presumes zstd library is installed14#include "common.h" // Helper functions, CHECK(), and CHECK_ZSTD()1516static void compress_orDie(const char* fname, const char* oname)17{18size_t fSize;19void* const fBuff = mallocAndLoadFile_orDie(fname, &fSize);20size_t const cBuffSize = ZSTD_compressBound(fSize);21void* const cBuff = malloc_orDie(cBuffSize);2223/* Compress.24* If you are doing many compressions, you may want to reuse the context.25* See the multiple_simple_compression.c example.26*/27size_t const cSize = ZSTD_compress(cBuff, cBuffSize, fBuff, fSize, 1);28CHECK_ZSTD(cSize);2930saveFile_orDie(oname, cBuff, cSize);3132/* success */33printf("%25s : %6u -> %7u - %s \n", fname, (unsigned)fSize, (unsigned)cSize, oname);3435free(fBuff);36free(cBuff);37}3839static char* createOutFilename_orDie(const char* filename)40{41size_t const inL = strlen(filename);42size_t const outL = inL + 5;43void* const outSpace = malloc_orDie(outL);44memset(outSpace, 0, outL);45strcat(outSpace, filename);46strcat(outSpace, ".zst");47return (char*)outSpace;48}4950int main(int argc, const char** argv)51{52const char* const exeName = argv[0];5354if (argc!=2) {55printf("wrong arguments\n");56printf("usage:\n");57printf("%s FILE\n", exeName);58return 1;59}6061const char* const inFilename = argv[1];6263char* const outFilename = createOutFilename_orDie(inFilename);64compress_orDie(inFilename, outFilename);65free(outFilename);66return 0;67}686970