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
Learning Poco: GET with HTTP
Learning Poco: A simple HTTP server
Learning Poco: Load XML Configuration
Learning Poco: Getting started with threads
Learning Poco: List directories recursively
CodeProject
License