diff options
| author | Thomas Schmucker <ts@its1.de> | 2026-07-12 15:19:57 +0200 |
|---|---|---|
| committer | Thomas Schmucker <ts@its1.de> | 2026-07-12 15:19:57 +0200 |
| commit | c17b523d4710134218bca4f2fdbe8fd0cee39ecd (patch) | |
| tree | 2d404a33440469804ef9f01162e52edb1bd70df4 /src/simple.c | |
| download | use-zlib-c17b523d4710134218bca4f2fdbe8fd0cee39ecd.tar.gz use-zlib-c17b523d4710134218bca4f2fdbe8fd0cee39ecd.tar.bz2 use-zlib-c17b523d4710134218bca4f2fdbe8fd0cee39ecd.zip | |
Erstes Beispiel für die Benutzung von zlib
Diffstat (limited to 'src/simple.c')
| -rw-r--r-- | src/simple.c | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/src/simple.c b/src/simple.c new file mode 100644 index 0000000..5209841 --- /dev/null +++ b/src/simple.c | |||
| @@ -0,0 +1,77 @@ | |||
| 1 | // Standard C | ||
| 2 | #include <stdio.h> | ||
| 3 | #include <stdlib.h> | ||
| 4 | |||
| 5 | // System | ||
| 6 | #include <unistd.h> | ||
| 7 | |||
| 8 | // zlib | ||
| 9 | #include <zlib.h> | ||
| 10 | |||
| 11 | static void | ||
| 12 | usage(void) | ||
| 13 | { | ||
| 14 | (void) fprintf(stderr, "compress [-d] infile outfile\n"); | ||
| 15 | exit(EXIT_FAILURE); | ||
| 16 | } | ||
| 17 | |||
| 18 | int | ||
| 19 | main(int argc, char *argv[]) | ||
| 20 | { | ||
| 21 | // int compress = 1; | ||
| 22 | int level = 5; | ||
| 23 | |||
| 24 | int opt = 0; | ||
| 25 | while ( (opt = getopt(argc, argv, "dl")) != -1 ) { | ||
| 26 | switch ( opt ) { | ||
| 27 | case 'd': | ||
| 28 | // compress = 0; // decompress | ||
| 29 | break; | ||
| 30 | |||
| 31 | case 'l': | ||
| 32 | level = 9; | ||
| 33 | break; | ||
| 34 | |||
| 35 | case '?': | ||
| 36 | default: | ||
| 37 | usage(); | ||
| 38 | break; | ||
| 39 | } | ||
| 40 | } | ||
| 41 | argc -= optind; | ||
| 42 | argv += optind; | ||
| 43 | |||
| 44 | if ( argc != 2 ) { | ||
| 45 | usage(); | ||
| 46 | } | ||
| 47 | |||
| 48 | FILE *in_file = fopen(argv[0], "rb"); | ||
| 49 | FILE *out_file = fopen(argv[1], "wb"); | ||
| 50 | |||
| 51 | (void) fseek(in_file, 0, SEEK_END); | ||
| 52 | unsigned long insize = ftell(in_file); // max 2GB... | ||
| 53 | (void) fseek(in_file, 0, SEEK_SET); | ||
| 54 | |||
| 55 | unsigned char *indata = malloc(insize); | ||
| 56 | (void) fread(indata, 1, insize, in_file); | ||
| 57 | |||
| 58 | unsigned long outsize = compressBound(insize); | ||
| 59 | unsigned char *outdata = malloc(outsize); | ||
| 60 | |||
| 61 | int res = compress2(outdata, &outsize, indata, insize, level); | ||
| 62 | |||
| 63 | if ( res == Z_OK ) { | ||
| 64 | (void) fwrite(outdata, 1, outsize, out_file); | ||
| 65 | } | ||
| 66 | else { | ||
| 67 | printf("Error: %d\n", res); | ||
| 68 | } | ||
| 69 | |||
| 70 | free(outdata); | ||
| 71 | free(indata); | ||
| 72 | |||
| 73 | (void) fclose(out_file); | ||
| 74 | (void) fclose(in_file); | ||
| 75 | |||
| 76 | return EXIT_SUCCESS; | ||
| 77 | } | ||
