Zlib outputting blank file

Hello, I wrote a program to compress a file with gzip, which works fine. I also wrote a program to decompress the gzip file, which runs but outputs a blank file. Any help would be greatly appreciated as the documentation on zlib's gzip functions is scarce at best.

Code:

main.cpp:
1
2
3
4
5
6
7
8
#include "decompress.h"
int main(int argc, const char * argv[]) {
    if(argc == 3)
    {
    decompressor(argv[1], argv[2]);
    }
    return 0;
}


decompress.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef unpack_decompress_h
#include <zlib.h>
#include <fstream>
#define unpack_decompress_h
void decompressor(const char *infile, const char *outfile)
{
    gzFile gin = gzopen(infile, "rb");
    unsigned int size = gztell(gin);
    char* buffer = new char[size];
    gzread(gin, buffer, size);
    std::ofstream of(outfile, std::ios::binary | std::ios::trunc);
    of.write(buffer,size);
    of.close();
    delete[] buffer;
}
#endif 
1
2
3
4
    gzFile gin = gzopen(infile, "rb"); // <- you open the file here... and since you never advance
    unsigned int size = gztell(gin);  //  the file pointer, it is still at 0.  Which means size == 0
    char* buffer = new char[size]; // <- so your buffer is 0 bytes in size
    gzread(gin, buffer, size);  // <- and you'd read 0 bytes 
Is this correct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef unpack_decompress_h
#include <zlib.h>
#include <fstream>
#define unpack_decompress_h
void decompressor(const char *infile, const char *outfile)
{
    gzFile gin = gzopen(infile, "rb");
    gzseek(gin, SEEK_END, 0);
    unsigned int size = gztell(gin);
    gzrewind(gin);
     char* buffer = new char[size];
    gzread(gin, buffer, size);
    std::ofstream of(outfile, std::ios::binary | std::ios::trunc);
    of.write(buffer,size);
    of.close();
    delete[] buffer;
}
#endif
gzseek takes file,offset,whence .... not file,whence,offset.

But the documentation states that gzseek doesn't support SEEK_END anyway.

You might not be able to determine the size of the file up front. Just read it in chunks until you hit EOF.
I would like to decompress the file into a buffer but it is becoming far more convoluted.

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef unpack_unpack_h
#include <zlib.h>
#include <stdio.h>
#include <stdlib.h>
#define unpack_unpack_h
void decompressor(const char *infile, const char *outfile) {
    FILE *in = fopen(infile, "rb"), *out = fopen(outfile, "wb");
    fseek(in , 0, SEEK_END);
    long size = ftell(in);
    fseek(in, 0, SEEK_SET);
    char* buffer = (char*)malloc(sizeof(char) * size);
    fread(buffer, 1, size, in);
    fwrite(buffer, sizeof(char), size, out);
    fclose(in);
    fclose(out);
    free(buffer);
}
#endif 
Last edited on
Topic archived. No new replies allowed.