libArchive modify data in .zip file -
i try modify( in memory ) 1 file in zip archive. not understand how it
i read source file memory not understand next
can give mу example how can this
why, here's simple c++11 example, replacing file , adding new file:
// g++ -std=c++11 -wall -g -o3 -fno-inline-functions pack.cc -o pack -larchive #include <iostream> using std::cout; using std::cerr; using std::endl; #include <memory> using std::shared_ptr; using std::unique_ptr; #include <string.h> #include <archive.h> // cygwin's libarchive. http://www.libarchive.org/ #include <archive_entry.h> int main (int argc, char** argv) { const char* usage = "usage: pack $in.zip $out.zip $pathtoreplace"; const char* infile = argc > 1 ? argv[1] : nullptr; if (!infile) {cerr << usage << endl; return 1;} const char* outfile = argc > 2 ? argv[2] : nullptr; if (!outfile) {cerr << usage << endl; return 1;} const char* pathtoreplace = argc > 3 ? argv[3] : nullptr; if (!pathtoreplace) {cerr << usage << endl; return 1;} shared_ptr<archive> in (archive_read_new(), [infile](archive* ar) {if (archive_read_finish (ar) != archive_ok) cerr << "error closing " << infile << endl;}); archive_read_support_format_zip (in.get()); // https://github.com/libarchive/libarchive/wiki/formatzip int rc = archive_read_open_filename (in.get(), infile, 65536); if (rc != archive_ok) {cerr << "error opening archive " << infile << endl; return 1;} shared_ptr<archive> out (archive_write_new(), [outfile](archive* ar) {if (archive_write_finish (ar) != archive_ok) cerr << "error closing " << outfile << endl;}); archive_write_set_format_zip (out.get()); rc = archive_write_open_filename (out.get(), outfile); if (rc != archive_ok) {cerr << "error opening archive " << outfile << endl; return 1;} archive_entry* entry; while (archive_read_next_header (in.get(), &entry) == archive_ok) { const char* path = archive_entry_pathname (entry); int64_t size = archive_entry_size (entry); char buf[size]; if (archive_read_data (in.get(), buf, size) != size) {cerr << "error reading " << path << endl; return 1;} if (strcmp (path, pathtoreplace) == 0 && size > 3) {strcpy (buf, "bar"); size = 3;} // replacing contents of given file. rc = archive_write_header (out.get(), entry); if (rc != archive_ok) {cerr << "error writing " << path << endl; return 1;} if (archive_write_data (out.get(), buf, size) != size) {cerr << "error writing " << path << endl; return 1;} } // add new file. unique_ptr<archive_entry, void(*)(archive_entry*)> (archive_entry_new(), archive_entry_free); archive_entry_set_pathname (we.get(), "foo"); archive_entry_set_size (we.get(), 3); archive_entry_set_filetype (we.get(), ae_ifreg); archive_entry_set_perm (we.get(), 0664); rc = archive_write_header (out.get(), we.get()); if (rc != archive_ok) {cerr << "error writing foo" << endl; return 1;} if (archive_write_data (out.get(), "bar", 3) != 3) {cerr << "error writing foo" << endl; return 1;} return 0; }
Comments
Post a Comment