c++ - C++ 的 gzstream 库 : corrupted file created

标签 c++ compression

我想用我的 C++ 脚本读取和写入压缩文件。为此,我使用 gzstream 库。它可以很好地使用一个非常简单的示例,如下所示:

string inFile="/path/inputfile.gz";
igzstream inputfile;
ogzstream outputfile("/path/outputfile.gz");
inputfile.open(inFile.c_str());

// Writing from input file to output file
string line;
while(getline(inputfile, line)) {
    outputfile << line << endl;
}

但在我的 C++ 脚本中,事情更加复杂,并且我的输出文件是在动态 vector 中创建的。

对于未压缩的文件,这种方法效果很好:

string inFile="/path/uncompressedInputFile.ext";
ifstream inputfile;
vector <ofstream *> outfiles(1);
string outputfile="/path/uncompressedOutputFile.ext";
outfiles[1] = new ofstream(outputfile.c_str());

inputfile.open(inFile.c_str());
string line;
while(getline(inputfile, line)) {
    *outfiles[1] << line << endl;
}

现在使用压缩文件,这种方式会产生损坏的文件:

string inFile="/path/compressedFile.gz";
igzstream inputfile;
vector <ogzstream *> outfiles(1);
string outputfile="/path/compressedOutputFile.gz";
outfiles[1] = new ogzstream(outputfile.c_str());

inputfile.open(inFile.c_str());
string line;
while(getline(inputfile, line)) {
    *outfiles[1] << line << endl;
}

我的路径中有一个“compressedOutputFile.gz”,不是空的,但是当尝试解压缩它时,我得到“意外的文件结尾”,我猜这意味着文件已损坏...... 它出什么问题了 ?谁能帮帮我吗 ?! :)

最佳答案

在这个简单的示例中,当 ofstream 被销毁时,GZip 文件会自动关闭,从而将其剩余缓冲区刷新到磁盘。

在动态示例中,您不会关闭,因为正在堆上创建对象。在这两种情况下,这都可能导致文件末尾的数据丢失,具体取决于格式。由于GZip经过压缩,因此更有可能丢失更多相关数据,从而导致更明显的失败。

最好的解决方案是创建一个 vector<unique_ptr<ogzstream> > ,这会导致流超出范围时自动销毁流。次优解决方案是记住在退出函数之前手动删除每个指针。

编辑:作为一个快速说明,正如 @doctorlove 在原始评论中指出的那样,您需要使用正确的索引,否则会导致其他问题。

关于c++ - C++ 的 gzstream 库 : corrupted file created,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19665744/

相关文章:

compression - 使用 gzip 时使用预先计算的数据

lua - 可以在 corona 中制作 zip 文件吗?

c++ - vector 的核心段错误

c++ - 如何在 Mac 上安装 VTK?

c++ - 如何尽可能以独立于平台的方式从 C++ 调用 .NET

c++ - 在 virtualenv 中使用 c++ 编译库

c# - GZipStream 只解压第一行

c# - 如何在C#中使用GZipStream解压?

有效地将每个字 rune 件的 4 个字符序列压缩为 2 位

c++ - 如何正确构建 OOP 和多文件项目?