Hello,
I'm learning C++, and i'm developing a simple zipper application, as my own, here is my code:
Code:
#include <string>
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <sstream>
#include "zlib.h"
using namespace std;
string compress_string(const 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(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];
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
ostringstream oss;
oss << "Exception during zlib compression: (" << ret << ") " << zs.msg;
throw(runtime_error(oss.str()));
}
return outstring;
}
int main(int argc, char* argv[])
{
string allinput;
while (cin.good()) // read all input from cin
{
char inbuffer[32768];
cin.read(inbuffer, sizeof(inbuffer));
allinput.append(inbuffer, cin.gcount());
}
string cstr = compress_string( allinput );
cerr << "Deflated data: "
<< allinput.size() << " -> " << cstr.size()
<< " (" << setprecision(1) << fixed
<< ( (1.0 - (float)cstr.size() / (float)allinput.size()) * 100.0)
<< "% saved).\n";
cout << cstr;
return 0;
}
Then i executed it normally, without errors, but when i try to open the archive i have some errors:
*.gz
Code:
gzip: /home/ubuntu/test.txt.gz: not in gzip format
*.zip
Code:
[/home/ubuntu/test.zip]
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
zipinfo: cannot find zipfile directory in one of /home/ubuntu/test.zip or
/home/ubuntu/test.zip.zip, and cannot find /home/ubuntu/test.zip.ZIP, period.
If you want to see the full discussion about this application, See Here
Thanks,
Nathan Paulino Campos