Click here to Skip to main content
Click here to Skip to main content

Learning Poco: Zip files

By , 18 Sep 2011
 

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:

#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

About the Author

stfairy
Student Shanghai Jiao Tong University
China China
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 18 Sep 2011
Article Copyright 2011 by stfairy
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid