Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Learning Poco: Zip Files

5.00/5 (1 vote)
18 Sep 2011CC (ASA 3U) 21.2K  
In this tutorial, we will zip files into a single archive file by using Poco::Zip::Compress.

In this tutorial, we will zip files into a single archive file by using Poco::Zip::Compress. We do not handle directories here but you may add this functionality by referencing the previous tutorial about listing directories recursively.

The Poco here stands for the POCO C++ libraries and is not to be confused with Plain Old CLR Object.

Create a file my_zip.cc with the following lines:

C++
#include <Poco/File.h>
#include <Poco/Path.h>
#include <Poco/Zip/Compress.h>
#include <iostream>
#include <fstream>

using namespace Poco;
using namespace Poco::Zip;
using namespace std;

int main(int argc, char **argv)
{
  if (argc < 2)
  {
    cout << "Usage: " << argv[0] 
    << " filename.zip [files...]" << endl;
    return -1;
  }

  ofstream out(argv[1], ios::binary);
  Compress c(out, true);
  for (int i = 2; i < argc; i++)
  {
    File f(argv[i]);
    if (f.exists())
    {
      Path p(f.path());
      if (f.isDirectory())
      {
        cout << "Ignore directory " << f.path() << endl;
      }
      else if (f.isFile())
      {
        cout << "Add file " << f.path() << endl;
        c.addFile(p, p.getFileName());
      }
    }
  }
  c.close();
  out.close();

  return 0;
}

Compile it and run:

$ g++ -o my_zip my_zip.cc -lPocoZip
$ ./my_zip
Usage: ./my_zip filename.zip [files...]
$ ./my_zip some.zip my_zip my_zip.cc
Add file my_zip
Add file my_zip.cc

You may unzip the file produced to check its validity.

Note that in order to handle (most importantly, recognize) directories correctly, we have to use File instead of Path, because Path::isDirectory only checks according to the string provided rather than the actual file-system structure.

For example, if you have some directory called testdir, Path(“testdir”).isDirectory() will be false while Path(“testdir/”).isDirectory() will be true. So we have to use File::isDirectory here.

Related Articles

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-Share Alike 3.0 Unported License