简体   繁体   中英

gzstream lib for C++ : corrupted file created

I want to read and write compressed file with my C++ script. For this purpose, I use the gzstream lib. It works fine with a very simple example like this :

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;
}

But in my C++ script, things are more complicated and my output files are created within a dynamic vector.

For UNcompressed files, this way worked very fine :

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;
}

Now with compressed file, this way produces me corrupted files :

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;
}

I got a "compressedOutputFile.gz" in my path, not empty, but when trying to uncompressed it I got "unexpected end of file" which, I guess, means the file is corrupted.... What's wrong with it ? Can anyone please help me ?! :)

In the simple example, the GZip file is closed automatically when the ofstream is destroyed, which flushes its remaining buffer to disk.

In the dynamic example, you're not closing because the object is being created on the heap. In both cases, this could result in the loss of data at the end of the file, depending on the format. Since GZip is compressed, it's more likely to lose more relevant data, resulting in a more obvious failure.

The best solution is to create a vector<unique_ptr<ogzstream> > , which cause it to automatically destroy streams when they go out of scope. The less optimal solution is to remember to manually delete each pointer prior to exiting the function.

Edit: And as a quick note, as pointed out by @doctorlove in the original comments, you need to use the correct index, otherwise you're causing other issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM