Friday, September 18, 2009

Simple zlib file reading example

This C++ example can read from both compressed and compressed files. It will read from testfile.gz (which can either be compressed or uncompressed) and write the contents to the standard output (screen).


#include "zlib.h"

#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
# include <fcntl.h>
# include <io.h>
# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
#else
# define SET_BINARY_MODE(file)
#endif

#include <iostream>

using namespace std;

int main(void) {

gzFile f = gzopen("testfile.gz","rb");

char buffer[1001];

for(;!gzeof(f);) {

int e = gzread(f,buffer,1000);
buffer[1000] = 0;
cout << buffer << endl;
}

gzclose(f);

}



Compile with g++ testprog.cpp -lz -o testprog

No comments: