Created
December 18, 2016 14:44
-
-
Save VictorZhang2014/224d80ddadbe4b255ed1114b9f8f143a to your computer and use it in GitHub Desktop.
zlib de/compress(es) file content rather than string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <zlib.h> | |
/* | |
* A good example for using zlib is correlated de/compress file instead of string | |
*/ | |
void decompress_one_file(char *infilename, char *outfilename); | |
void compress_one_file(char *infilename, char *outfilename); | |
int main(int argc, char **argv) | |
{ | |
compress_one_file(argv[1],argv[2]); | |
decompress_one_file(argv[2],argv[3]); | |
} | |
unsigned long file_size(char *filename) | |
{ | |
FILE *pFile = fopen(filename, "rb"); | |
fseek (pFile, 0, SEEK_END); | |
unsigned long size = ftell(pFile); | |
fclose (pFile); | |
return size; | |
} | |
void decompress_one_file(char *infilename, char *outfilename) | |
{ | |
gzFile infile = gzopen(infilename, "rb"); | |
FILE *outfile = fopen(outfilename, "wb"); | |
if (!infile || !outfile) return; | |
char buffer[128]; | |
int num_read = 0; | |
while ((num_read = gzread(infile, buffer, sizeof(buffer))) > 0) { | |
fwrite(buffer, 1, num_read, outfile); | |
} | |
gzclose(infile); | |
fclose(outfile); | |
} | |
void compress_one_file(char *infilename, char *outfilename) | |
{ | |
FILE *infile = fopen(infilename, "rb"); | |
gzFile outfile = gzopen(outfilename, "wb"); | |
if (!infile || !outfile) return; | |
char inbuffer[128]; | |
int num_read = 0; | |
unsigned long total_read = 0, total_wrote = 0; | |
while ((num_read = fread(inbuffer, 1, sizeof(inbuffer), infile)) > 0) { | |
total_read += num_read; | |
gzwrite(outfile, inbuffer, num_read); | |
} | |
fclose(infile); | |
gzclose(outfile); | |
printf("Read %ld bytes, Wrote %ld bytes, Compression factor %4.2f%%\n", | |
total_read, file_size(outfilename), | |
(1.0-file_size(outfilename)*1.0/total_read)*100.0); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment