Вибір засобів для реалізації програми 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Вибір засобів для реалізації програми

Поиск

4. Вибір засобів для реалізації програми

 

Програма була написана для терміналу за процедурною парадигмою програмування мовою с++ в середовищі DEVc++.

        

 

5. Структура, інтерфейс та опис програми

 

Після запуску програми користувачу пропонується ввести назву файлу, який потрібно архівувати. З цього файлу буде зчитано вхідне повідомлення.

Потім створюється базовий словник ( довжина слів якого 1 символ), після чого відбувається процес кодування, алгоритм якого наведений вище. В результаті кодування створюється вектор строкових змінних, котрі заповнені символами 0 і 1.

Наступним кроком створюється вихідний файл «out_x.txt», в який записується закодоване повідомлення. На цьому робота архіватора завершується.

Після запуску розархіватора відбувається процес декодування (з символьних змінних до вихідного повідомлення). Для декодування програма зчитує дані з файлу «out_x.txt».

По завершенню роботи програма виводить у вихідний файл «out_y.txt» вихідне повідомлення.

 

 

6. Текст програми

 

Текст кодера:

#include <fstream>

#include <iostream>

#include <vector>

#include <string>

#include <cstdlib>

#include <cstdio>

#include <sstream>

using namespace std;

 

string itos(int number)

{

    stringstream ss;

    ss << number;

    string str = ss.str();

    return str;

}

 

string check(string temp, vector<string> &myvector)

{

    string buf;

    for(int i=0; i < myvector.size(); i++)

              if(myvector[i] == temp)

              {

                       buf = itos(i);

                       return buf;

              }

    buf = "0";

    return buf;

}

 

string mirror(string buf)

{

    string res;

    for(int i=buf.length()-1; i>=0; i--)

    {

              res += buf[i];

    }

    return res;

}

 

string codeToBinary(string code)

{

    int temp, buf;

    string res;

    temp = atoi(code.c_str());

        

    while(buf != 0)

    {

              buf = temp / 2;

              if(buf * 2 == temp)

                       res += '0';

              else

                       res += '1';

              temp /= 2;

    }

 

    return mirror(res);

}

 

int MaxCdSz(vector<string> code)

{

    int res = 0;

    for(int i=0; i < code.size(); i++)

    {

              if(code[i].length() > res)

                       res = code[i].length();

    }

    return res;

}

 

string codeaddon(string code, char code_length)

{

    string res;

    if(code.length() < code_length)

    {

              int c = code_length - code.length();

              for(int i=0; i < c; i++)

                       res += '0';

              for(int i=0; i < code.length(); i++)

                       res += code[i];

              return res;

    }

    return code;

}

 

int main()

{

    string file;

    cout<<"enter file name: ";

    cin>>file;

 

    ifstream iff(file.c_str(), ios::binary);

 

    if(!iff)

    {

              cout<<"file does not exist"<<endl;

              exit(0);

    }

 

    string temp;

    char buf;

 

    iff.seekg(0, iff.end);

    int filelength = iff.tellg();

    iff.seekg(0, iff.beg);

 

    if(!filelength)

    {

              cout<<"input file is empty"<<endl;

              iff.close();

              exit(0);

    }

 

    vector<string> myvector;

    string newletter;

 

    for(int i=0; i < 256; i++)

    {

              buf = i;

 

              newletter = buf;

              myvector.push_back(newletter);

    }

 

    string P, C, PC;

    vector<string> code;

 

    for(int j=0; j < filelength; j++)

    {

              iff.get(buf);

              C = buf;

              PC = P + C;

              if(check(PC, myvector) == "0")

              {

                       newletter = PC;

                       myvector.push_back(newletter);

                       code.push_back(check(P, myvector));

                       P = C;

              }

              else

              {

                       P = PC;

              }

    }

    code.push_back(check(P, myvector));

 

    iff.close();

 

    ofstream off("offile.txt", ios::binary);

 

        

 

    for(int k=0; k < code.size(); k++)

              code[k] = codeToBinary(code[k]);

 

    char cdsz = MaxCdSz(code);

    off<<cdsz;

    for(int k=0; k < code.size(); k++)

              code[k] = codeaddon(code[k], cdsz);

 

    string result;

    for(int k=0; k < code.size(); k++)

              result += code[k];

 

    char buffer = 0;

    int j=0;

 

    for (int i=0; i < result.length(); i+=8)

    {

              buffer = 0;

              for (j=0; j < 7; j++)

              {

                       if (result[i+j] == '1')

                       {

                                 buffer += 1;

                                 buffer <<= 1;

                       }

                       else

                                 buffer <<= 1;

              }

              if (result[i+j] == '1')

                       buffer += 1;

 

              off<<buffer;

    }

 

    off.close();

}

Текст декодера:

#include <fstream>

#include <iostream>

#include <vector>

#include <string>

#include <cstdlib>

#include <cmath>

#include <cstdio>

#include <sstream>

using namespace std;

 

string itos(int number)

{

    stringstream ss;

    ss << number;

    string str = ss.str();

    return str;

}

 

string check(string temp, vector<string> &myvector)

{

    string buf;

    for(int i=0; i < myvector.size(); i++)

              if(myvector[i] == temp)

              {

                       buf = itos(i+1);

                       return buf;

              }

    buf = "0";

    return buf;

}

 

int main()

{

    ifstream iff("offile.txt", ios::binary);

 

    if(!iff)

    {

              cout<<"file does not exist"<<endl;

              exit(0);

    }

 

    string temp;

    char buf;

 

    iff.seekg(0, iff.end);

    int filelength = iff.tellg();

    iff.seekg(0, iff.beg);

 

    if(!filelength)

    {

              cout<<"input file is empty"<<endl;

              iff.close();

              exit(0);

    }

 

    char cdsz;

    iff.get(cdsz);

 

    vector<string> myvector;

    string newletter;

 

    for(int i=0; i < 256; i++)

    {

              buf = i;

 

              newletter = buf;

              myvector.push_back(newletter);

    }

 

    vector<string> codes;

        

 

    ofstream off("res", ios::binary);

 

    int count8 = 0, j=0;

    buf = 0;

    temp.clear();

    iff.get(buf);

 

    while(!iff.eof())

    {

              while((j < cdsz) && !iff.eof())

              {

                       if((buf>>(7 - (count8 % 8))) & 1)

                                 temp += '1';

                       else

                                 temp += '0';

                       count8++;

                       j++;

                       if(!(count8 % 8))

                                 iff.get(buf);

              }

 

              j =0;

              codes.push_back(temp);

              temp.clear();

    }

 

    if(codes[codes.size() - 1].length() < cdsz)

              codes.pop_back();

 

    vector<int> code;

 

    int bufint = 0, i, k;

    for(int j=0; j<codes.size(); j++)

    {

              for(i = cdsz - 1, k=0; i>=0; i--, k++)

                       if(codes[j][i] == '1')

                                 bufint += pow(2, k);

              code.push_back(bufint);

              bufint = 0;

    }

 

    string P, C, PC;

        

    for(int i=0; i<code.size(); i++)

    {

              C = myvector[code[i]];

              off<<C;

              if(i == 0)

                       P = C;

              else

              {

                       PC = P + C[0];

                       if(check(PC, myvector) == "0")

                       {

                                 newletter = PC;

                                 myvector.push_back(newletter);

                                 P = C;

                       }

              }

    }

 

    iff.close();

    off.close(); 

}

 

 



Поделиться:


Последнее изменение этой страницы: 2024-06-27; просмотров: 42; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 216.73.217.21 (0.006 с.)