Dario de Judicibus said:
I wish to implement a simple C++ filter that reads from a file byte by byte
and writes to an output files two bytes for each byte read according to some
hardcoded table. I am looking for a very straightforward sample. It is
pratically a binary filter.
Thank you in advance.
#include <fstream>
#include <ios>
#include <iostream>
#include <limits>
#include <map>
#include <string>
void show_table(const std::map<unsigned char,
std::basic_string<unsigned char> >&t)
{
std::map<unsigned char,
std::basic_string<unsigned char> >
::const_iterator it(t.begin());
while(it != t.end())
{
std::cout << unsigned int(it->first) << ": ";
for(std::string::size_type i = 0; i != it->second.size(); ++i)
std::cout << unsigned int(it->second
) << ", ";
std::cout << '\n';
++it;
}
}
int main()
{
std::map<unsigned char, std::basic_string<unsigned char> > table;
unsigned char hi(std::numeric_limits<unsigned char>::max());
unsigned char c(hi);
while(c)
{
table[c] = std::basic_string<unsigned char>(2, hi - c);
--c;
}
table[c] = std::basic_string<unsigned char>(2, hi - c);
show_table(table);
std::basic_ifstream<unsigned char> input("input", std::ios::binary);
std::basic_ofstream<unsigned char> output("output", std::ios::binary);
if(input && output)
{
unsigned char c(0);
while(input.get(c))
{
std::basic_string<unsigned char> s(table[c]);
if(!output.write(s.c_str(), s.size()))
break;
}
}
return 0;
}
-Mike