我一直在寻找一个好的、便携式的方法来在C++中创建zip文件,但一直没有成功。我在各种地方都看到过使用Boost IOstream库的可能性,但是在参考文献中我找不到任何源代码或甚至文档:
http://www.boost.org/doc/libs/1_48_0/libs/iostreams/doc/index.html
有没有什么好的参考资料?我已经做了很多谷歌搜索,但没有找到太多有用的信息。
我一直在寻找一个好的、便携式的方法来在C++中创建zip文件,但一直没有成功。我在各种地方都看到过使用Boost IOstream库的可能性,但是在参考文献中我找不到任何源代码或甚至文档:
http://www.boost.org/doc/libs/1_48_0/libs/iostreams/doc/index.html
有没有什么好的参考资料?我已经做了很多谷歌搜索,但没有找到太多有用的信息。
ZipFileWriter zip("foo.zip");
std::ostream* o = zip.Add_File("test.txt");
*o << "look a zip file" << std::endl;
delete o;
std::ostream* o2 = zip.Add_File("test2.txt");
*o2 << "look another file" << std::endl;
delete o2;
然后可以通过执行以下操作来读取文件
ZipFileReader zip("foo.zip");
std::istream* i = zip.Get_File("test.txt");
std::string foo;
*i >> foo;
std::cout << foo << std::endl;
delete i;
#include <fstream>
#include <sstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/zlib.hpp>
TEST(MyTests, SaveZipFile)
{
using namespace std;
ofstream file("a.z", ios_base::out | ios_base::binary);
boost::iostreams::filtering_streambuf<boost::iostreams::output> out;
out.push(boost::iostreams::zlib_compressor());
out.push(file);
stringstream sstr{"nihao"};
boost::iostreams::copy(sstr, out);
}
TEST(MyTests, OpenZipFile)
{
using namespace std;
ifstream file("a.z", ios_base::in | ios_base::binary);
boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
in.push(boost::iostreams::zlib_decompressor());
in.push(file);
stringstream sstr;
boost::iostreams::copy(in, sstr);
cout << sstr.str() << endl;
ASSERT_EQ(sstr.str(), string("nihao"));
}
char* buf=new char[std::max(comment_length,std::max(filename_length,extra_length))];
istream.read(buf,filename_length);
buf[filename_length]=0;
这忽略了缓冲区需要一个额外的字符空间来存放终止符(第193行),可能破坏堆!因此,第191行应该改为
char* buf=new char[std::max(comment_length,std::max(static_cast<unsigned short>(filename_length+1),extra_length))];
所以,如果你要使用这个类,你应该考虑修复这个 bug。这很容易。