
Patrick B. answered 06/05/20
Math and computer tutor/teacher
using namespace std;
#include <iostream>
#include <string.h>
#define WORD_LEN (16)
#define MAX_LINES (1024)
typedef struct _TWord
{
char bitstr[WORD_LEN+1];
int intstr[WORD_LEN];
int iCount;
int startingBit;
}*TWord;
#define WORD_SIZE (sizeof(struct _TWord))
#define TWORD_SIZE (sizeof(TWord))
int bits2Ints(TWord word)
{
int bitStreak=1;
word->startingBit = (word->bitstr[0]=='1') ? 1 : 0;
word->iCount=0;
for (int iLoop=0; iLoop<WORD_LEN-1; iLoop++)
{
if ( word->bitstr[iLoop]!=word->bitstr[iLoop+1])
{
word->intstr[word->iCount++] = bitStreak;
bitStreak=1;
}
else
{
bitStreak++;
}
}
word->intstr[word->iCount++] = bitStreak;
}
ints2Bits(TWord word)
{
char curBit = (word->startingBit==1) ? '1' : '0';
int iIndexPos=-1;
for (int iLoop=0; iLoop<word->iCount; iLoop++)
{
for (int jLoop=0; jLoop<word->intstr[iLoop]; jLoop++)
{
word->bitstr[++iIndexPos]=curBit;
}
if (curBit=='1')
{
curBit='0';
}
else
{
curBit='1';
}
}
word->bitstr[WORD_LEN]=0;
}
DumpWord(TWord word)
{
cout << word->bitstr << endl;
for (int iLoop=0; iLoop<word->iCount; iLoop++)
{
cout << word->intstr[iLoop] << endl;
}
cout << " starting bit " << word->startingBit << endl;
}
int Compress ( char * input_filename, char * output_filename )
{
char A[MAX_LINES][WORD_LEN];
struct _TWord word[MAX_LINES];
int iLineCount=0;
int iLoop;
int wordCount =0;
FILE * infile = fopen(input_filename,"r");
FILE * outfile = fopen(output_filename,"w");
for (iLoop=0; iLoop<MAX_LINES; iLoop++)
{
if (fscanf(infile,"%s",A[iLoop])== EOF)
{
cout << A[iLoop] << endl;
break;
}
cout << A[iLoop] << endl;
}
iLineCount = iLoop;
cout << iLineCount << " lines compressed " << endl;
for (iLoop=0; iLoop<iLineCount; iLoop++)
{
strcpy(word[iLoop].bitstr,A[iLoop]);
bits2Ints(&word[iLoop]); //compression takes place here
DumpWord(&word[iLoop]);
fprintf(outfile,"%d %d ",word[iLoop].startingBit,word[iLoop].iCount);
for (int jLoop=0; jLoop<word[iLoop].iCount; jLoop++)
{
fprintf(outfile," %d ",word[iLoop].intstr[jLoop]);
}
fprintf(outfile,"\n");
}
fclose(infile);
fclose(outfile);
return(iLoop);
}
int Decompress( char * input_filename, char * output_filename)
{
struct _TWord word[MAX_LINES];
int iLineCount=0;
int iLoop;
int wordCount =0;
FILE * infile = fopen(input_filename,"r");
FILE * outfile = fopen(output_filename,"w");
for (iLoop=0; iLoop<MAX_LINES; iLoop++)
{
if (fscanf(infile,"%d %d",&word[iLoop].startingBit, &word[iLoop].iCount)!=EOF)
{
for (int jLoop=0; jLoop<word[iLoop].iCount; jLoop++)
{
fscanf(infile,"%d",&word[iLoop].intstr[jLoop]);
}
ints2Bits(&word[iLoop]);
fprintf(outfile,"%s\n",word[iLoop].bitstr);
}
else
{
break;
}
}
fclose(infile);
fclose(outfile);
return(iLoop);
}
int main()
{
Compress( (char*)"data.txt",(char*)"compressed.txt");
Decompress ((char*) "compressed.txt",(char *) "copydata.txt ");
}