C++: Zipping a file (you can only use the headers #include <fstream> #include <s
ID: 3890363 • Letter: C
Question
C++: Zipping a file (you can only use the headers
#include <fstream>
#include <string>
#include <algorithm>)
My code that doesn't work: (this works for most files, but if there are an uneven amount of blocks (e.g 1111222233334444----4444333322221111) the code doesn't work)
#include <iostream>
#include <fstream>
using namespace std;
void unzip_file(const std::string& filename){
streampos size;
char * memblock;
string in;
string out;
in = filename;
out = filename + "-zipped";
ifstream file (in.c_str(), ios::in|ios::binary);
ofstream ofile (out.c_str(), ios::out|ios::binary);
if (file)
{
file.seekg (0, ios::end);
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
for (int i = 0; i<size/2; i = i+4){
ofile.write(&memblock[size/2+i],4);
ofile.write(&memblock[i],4);
}
ofile.close();
delete[] memblock;
}
}
int main () {
string filename;
cout << "Enter file name :" << endl;
cin >> filename;
unzip_file(filename);
}
Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
void unzip_file(const std::string& filename){
streampos size;
char * memblock;
string in;
string out;
int size1;
in = filename;
out = filename + "-zipped";
int n;
ifstream file (in.c_str(), ios::in|ios::binary);
ofstream ofile (out.c_str(), ios::out|ios::binary);
if (file)
{
file.seekg (0, ios::end);
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
n = size/4;
if (n % 2 != 0)
n = size/2 -2;
else
n = size/2;
cout << size << " " << n << endl;
for (int i = 0; i<n; i = i+4){
ofile.write(&memblock[n+i],4);
ofile.write(&memblock[i],4);
}
size1 = size;
if (n == (size/2) -2){
ofile.write(&memblock[size1-4],4);
}
ofile.close();
delete[] memblock;
}
}
int main () {
string filename;
cout << "Enter file name :" << endl;
cin >> filename;
unzip_file(filename);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.