Hello,
I'm learning C++ and i was trying to use the zlib, but i'm getting some errors when trying to compile my little project. Here is the code:
#include <string>
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <zlib.h>
using namespace std;
std::string compress_string(const std::string& str,
int compressionlevel = Z_BEST_COMPRESSION)
{
z_stream zs; // z_stream is zlib's control structure
memset(&zs, 0, sizeof(zs));
if (deflateInit(&zs, compressionlevel) != Z_OK)
throw(std::runtime_error("deflateInit failed while compressing."));
zs.next_in = (Bytef*)str.data();
zs.avail_in = str.size(); // set the z_stream's input
int ret;
char outbuffer[32768];
std::string outstring;
// retrieve the compressed bytes blockwise
do {
zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
zs.avail_out = sizeof(outbuffer);
ret = deflate(&zs, Z_FINISH);
if (outstring.size() < zs.total_out) {
// append the block to the output string
outstring.append(outbuffer,
zs.total_out - outstring.size());
}
} while (ret == Z_OK);
deflateEnd(&zs);
if (ret != Z_STREAM_END) { // an error occurred that was not EOF
std::ostringstream oss;
oss << "Exception during zlib compression: (" << ret << ") " << zs.msg;
throw(std::runtime_error(oss.str()));
}
return outstring;
}
int main(int argc, char* argv[])
{
std::string allinput;
while (std::cin.good()) // read all input from cin
{
char inbuffer[32768];
std::cin.read(inbuffer, sizeof(inbuffer));
allinput.append(inbuffer, std::cin.gcount());
}
std::string cstr = compress_string( allinput );
std::cerr << "Deflated data: "
<< allinput.size() << " -> " << cstr.size()
<< " (" << std::setprecision(1) << std::fixed
<< ( (1.0 - (float)cstr.size() / (float)allinput.size()) * 100.0)
<< "% saved).\n";
std::cout << cstr;
}
And here is my compiling log:
ubuntu@eeepc:~$ g++ comp.cpp -o comp
/tmp/ccTx0M9f.o: In function `compress_string(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)':
comp.cpp:(.text+0x1e3): undefined reference to `deflateInit_'
comp.cpp:(.text+0x394): undefined reference to `deflate'
comp.cpp:(.text+0x412): undefined reference to `deflateEnd'
collect2: ld returned 1 exit status
ubuntu@eeepc:~$
Thanks,
Nathan Paulino Campos