I was trying to write a primitive code that
would compress a text file by changing every character into a series of bits (length depends on the number of characters)
and after all of this is done the script would take all of these bits put them into one string add more bits if necessary(to make the size of binary string multiple of 8)
and then change groups of 8 bits to their ASCII value
and everything seems to be working ok but and the end when I try to save the compressed string,
I check to see how it looks and it's just a bunch of random characters.
I don't know what went wrong
#include <iostream>
#include <string>
#include <bitset>
#include <map>
#include <vector>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <sstream>
using namespace std;
int main()
{
vector<char> lista;
map<char,string> znaki;
string szyfr;
char ch;
fstream file;
file.open( "test.txt", std::ios::in | std::ios::out );
while(file >> ch)
{
if(find(lista.begin(), lista.end(), ch) == lista.end())
{
lista.push_back(ch);
}
}
sort(lista.begin(), lista.end());
int lista_rozm=lista.size();
string dekod;
dekod+=bitset<8>(lista_rozm).to_string();
int length = ceil(log2(lista.size()));
for(int i=0;i<lista.size();i++){
dekod+=lista[i];
string binaryString = bitset<8>(i).to_string();
if (binaryString.size() > length)
binaryString = binaryString.substr(binaryString.size() - length);
else if (binaryString.size() < length)
binaryString = std::string(length - binaryString.size(), '0') + binaryString;
znaki.insert(pair<char,string>(lista[i],binaryString));
}
file.close();
file.open( "test.txt", std::ios::in | std::ios::out );
char ch2;
while(file >> ch2){
szyfr+=znaki[ch2];
}
while((szyfr.size() % 8)!=0){
szyfr+='1';
}
stringstream sstream(szyfr);
string output;
while(sstream.good()){
bitset<8> bits;
sstream >> bits;
output += char(bits.to_ulong());
cout<<output<<endl;
}
dekod+=output;
//cout<<dekod;
file.close();
fstream file2;
file2.open("wynik.txt", ios::out );
file2<<output;
file2<<dekod;
//cout<<dekod;
file2.close();
return 0;
}
Like i said i tried to make a code that would compress a txt file but i failed