Please work on C++ You can ONLY use given #include code you are working on #incl
ID: 3889618 • Letter: P
Question
Please work on C++
You can ONLY use given #include
code you are working on
#include <fstream>
#include <string>
#include <algorithm>
void unzip_file(const std::string& filename) {
//TODO
}
Test code(cannot change):
#include <iostream>
int main() {
std::string testFilename;
// Tests your unzip_file function on test01 through test09
for (int i = 1; i <= 9; ++i) {
testFilename = std::string("test0") + (char) (i + 48);
// Test your unzip_file function.
unzip_file(testFilename);
if (cmp_files(testFilename + "-unzipped", testFilename + "-unzipped-expected")) {
std::cout << "Unzipping the file went as expected!" << std::endl;
} else {
std::cout << "Something went wrong unzipping the file. :(" << std::endl;
return -1;
}
}
Explanation / Answer
Given below is the implementation of unzip_file(), please use this code in your files and test it test code. Since the test files are not provided, I can not test it. Post a comment in case of any issues and I shall fix it. If works well for you, please don't forget to rate the answer . Thank you.
void unzip_file(const string& filename)
{
ifstream infile(filename.c_str(), ios::binary);
if(!infile.is_open())
{
cout << "Error opening input file " << filename << endl;
return;
}
string outfname = filename + "-unzipped"; //generate the output filename
ofstream outfile(outfname.c_str(), ios::binary);
if(!outfile.is_open())
{
cout << "Error opening output file " << outfname << endl;
return;
}
char block[4]; //4 bytes
//first, write every odd block of 4 bytes to output file
while(true)
{
infile.read(block, 4); //read 4 bytes of data
if(infile.fail()) //if the read failed because of eof, then stop
break;
infile.seekg(4, ios::cur); //skip 4 bytes from current, i.e skip an even block
outfile.write(block, 4); //write 4 bytes of data to output file
}
//come back to begining of file, and start writing even blocks of 4 bytes
infile.clear();//clear any flags when eof was reached
infile.seekg(0, ios::beg); //go back to begginng of file
while(true)
{
infile.seekg(4, ios::cur); //skip 4 bytes from current location, i.e. skip an odd block
infile.read(block, 4); //read 4 bytes of data
if(infile.fail()) //read failed because of eof, then stop
break;
outfile.write(block, 4); //write 4 bytes of data to output file
}
infile.close();
outfile.close();
cout << "output file " << outfname << " generated." << endl;
}