Click to See Complete Forum and Search --> : Wierd. ZLIB compression/uncompression problems...


quantass
January 27th, 2003, 11:08 PM
I just cant get the following code to work. First off the ZLIB compressor isnt compressing/uncompressing correctly (the src is originally 680kb, compressed = 78kb, uncompressed = 80kb) and many times over the statement: inp.open("d:\\Test20.zip", ios::binary); in the "uncompress area" isnt able to open the file for some reason setting "inp" to 0. What am i doing wrong within the following code?

The zlib header, libz.lib, and zlib.dll are available.

---
// ZLIB.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include "zlib.h"
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
char *des, *src;
unsigned long desLen, tdesLen, srcLen, rlen;
std::ifstream inp;
std::ofstream oup;

/////////////////////////////////////////
// Compress Test20.exe to Test20.zip
/////////////////////////////////////////
inp.open("d:\\Test20.exe", ios::binary);
oup.open("d:\\Test20.zip", ios::binary);

srcLen=3000;
desLen=tdesLen=srcLen*1.001+12;

src=new char[srcLen];
des=new char[desLen];

inp.read(src,srcLen);
rlen=inp.gcount();

while(rlen)
{
compress2((Bytef *) des,&tdesLen,(Bytef *)src,rlen,2);
oup.write(des,tdesLen);
tdesLen=desLen;
inp.read(src,srcLen);
rlen=inp.gcount();
}

oup.close();
inp.close();


/////////////////////////////////////////
// Uncompress Test20.zip to Test20B.exe
/////////////////////////////////////////
inp.open("d:\\Test20.zip", ios::binary);
oup.open("d:\\Test20B.exe", ios::binary);

srcLen=3000;
desLen=tdesLen=srcLen*1.001+12;

inp.read(src,srcLen);
rlen=inp.gcount();

while(rlen)
{
uncompress((Bytef *) des,&tdesLen,(Bytef *)src,rlen);
oup.write(des,tdesLen);
tdesLen=desLen;
inp.read(src,srcLen);
rlen=inp.gcount();
}

oup.close();
inp.close();


return 0;
}

---

mwilliamson
January 28th, 2003, 09:21 AM
You can't store a file in a char array! chars are null terminated, if your file contains a null character you will get the behaviour you are experiancing. Store your files in BYTE arrays and use memcpy to copy.

Philip Nicoletti
January 28th, 2003, 09:55 AM
If using a ifstream for more than one file like you are,
you need to clear the state ...


oup.close();
inp.close();

// add these lines ...

oup.clear();
inp.clear();

DanM
January 28th, 2003, 11:33 AM
You can store whatever you want in a char array - even binary data - as long as you don't treat them like strings i.e. expect strlen/strcpy to work OK. Use can use memcpy on a char array without any problem.

There are a lot of APIs that use char*/const char* without the referenced data being a string - setsockopt, for example:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/setsockopt_2.asp

Dan