
Лаб. 1 ЗИ
.docxЛабораторная работа №1
Статистические свойства открытых текстов
Цели работы:
1) Получить представление о статистических свойствах открытых текстов.
2) Понять, как влияет на статистические свойства текстов их представление в
компьютере.
3) Научиться создавать программы, которые реализуют простейшие
шифрпреобразования.
#include
<iostream>
#include <omp.h>
#include <fstream>
using namespace std;
void n1(const char *filename) {
ifstream file(filename, ios::binary);
if (!file) {
cerr << "Ошибка открытия файла!" << endl;
}
// указатель на конец файла
file.seekg(0, ios::end);
// текущая позиция (длина файла)
streamsize length = file.tellg();
file.close();
cout << "Длина файла в байтах: " << length << endl;
}
int main() {
setlocale(LC_ALL, "Rus");
const char* filename = "C:/Users/user/source/repos/ZI_LAB_1/x64/Debug/lab1.doc";
n1(filename);
return 0;
}
#include <iostream>
#include <omp.h>
#include <fstream>
#include <vector>
using namespace std;
void n1(const char* filename) {
ifstream file(filename, ios::binary);
if (!file) {
cerr << "Ошибка открытия файла!" << endl;
return;
}
// указатель на конец файла
file.seekg(0, ios::end);
// текущая позиция (длина файла)
streamsize length = file.tellg();
file.close();
cout << "Длина файла в байтах: " << length << endl;
}
void n2(const char* filename) {
ifstream file(filename, ios::binary);
if (!file) {
cerr << "Ошибка открытия файла!" << endl;
return;
}
// вектор для хранения частот байтов
vector<long long> frequencies(256, 0);
char byte;
long long totalBytes = 0;
// подсчёт частот
while (file.get(byte)) {
frequencies[static_cast<unsigned char>(byte)]++;
totalBytes++;
}
file.close();
cout << "Относительные частоты появления байтов:" << endl;
for (int i = 0; i < 256; i++) {
if (frequencies[i] > 0) {
cout << "Байт " << i << " (символ '" << static_cast<char>(i) << "'): "
<< static_cast<double>(frequencies[i]) / totalBytes << endl;
}
}
}
int main() {
//system("chcp 65001");
setlocale(LC_ALL, "Rus");
const char* filename = "C:/Users/user/source/repos/ZI_LAB_1/x64/Debug/lab1.txt";
n1(filename);
n2(filename);
return 0;
}
#include <iostream>
#include <fstream>
#include <vector>
#include <random>
#include <unordered_map>
#include <set>
using namespace std;
void n1(const char* filename) {
ifstream file(filename, ios::binary);
if (!file) {
cerr << "Ошибка открытия файла!" << endl;
return;
}
// указатель на конец файла
file.seekg(0, ios::end);
// текущая позиция (длина файла)
streamsize length = file.tellg();
file.close();
cout << "Длина файла в байтах: " << length << endl;
}
void n2(const char* filename) {
ifstream file(filename, ios::binary);
if (!file) {
cerr << "Ошибка открытия файла!" << endl;
return;
}
// вектор для хранения частот байтов
vector<long long> frequencies(256, 0);
char byte;
long long totalBytes = 0;
// подсчёт частот
while (file.get(byte)) {
frequencies[static_cast<unsigned char>(byte)]++;
totalBytes++;
}
file.close();
cout << "Относительные частоты появления байтов:" << endl;
for (int i = 0; i < 256; i++) {
if (frequencies[i] > 0) {
cout << "Байт " << i << " (символ '" << static_cast<char>(i) << "'): "
<< static_cast<double>(frequencies[i]) / totalBytes << endl;
}
}
}
void n3(const char* inputFilename) {
const char* keyFilename = "key.txt";
const char* encryptedFilename = "new_lab1.txt";
const char* decryptedFilename = "old_lab1.txt";
// генерация ключа
ofstream keyFile(keyFilename);
if (!keyFile) {
cerr << "Ошибка создания key.txt!" << endl;
return;
}
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int> dis(0, 255);
unordered_map<unsigned char, unsigned char> keyMap;
set<unsigned char> usedBytes;
for (int i = 0; i < 256; i++) {
unsigned char originalByte = static_cast<unsigned char>(i);
unsigned char newByte;
// генерация уникального нового байта
do {
newByte = static_cast<unsigned char>(dis(gen));
} while (usedBytes.count(newByte) > 0);
usedBytes.insert(newByte);
keyMap[originalByte] = newByte;
keyFile << static_cast<int>(originalByte) << " " << static_cast<int>(newByte) << endl;
}
keyFile.close();
// шифрование
ifstream inputFile(inputFilename, ios::binary);
ofstream outputFile(encryptedFilename, ios::binary);
if (!inputFile || !outputFile) {
cerr << "Ошибка открытия файла для шифрования!" << endl;
return;
}
char byte;
while (inputFile.get(byte)) {
outputFile.put(keyMap[static_cast<unsigned char>(byte)]);
}
inputFile.close();
outputFile.close();
// дешифрование
ifstream encryptedFile(encryptedFilename, ios::binary);
ofstream decryptedFile(decryptedFilename, ios::binary);
if (!encryptedFile || !decryptedFile) {
cerr << "Ошибка открытия файла для дешифрования!" << endl;
return;
}
unordered_map<unsigned char, unsigned char> reverseKeyMap;
for (const auto& pair : keyMap) {
reverseKeyMap[pair.second] = pair.first;
}
while (encryptedFile.get(byte)) {
decryptedFile.put(reverseKeyMap[static_cast<unsigned char>(byte)]);
}
encryptedFile.close();
decryptedFile.close();
// сравнение файлов
ifstream originalFile(inputFilename, ios::binary);
ifstream recoveredFile(decryptedFilename, ios::binary);
bool filesMatch = true;
char originalByte, recoveredByte;
while (true) {
bool originalRead = originalFile.get(originalByte).good();
bool recoveredRead = recoveredFile.get(recoveredByte).good();
if (originalRead != recoveredRead) {
filesMatch = false; // один файл закончился, а другой нет
break;
}
if (!originalRead) break; // оба файла закончились
if (originalByte != recoveredByte) {
filesMatch = false;
break;
}
}
originalFile.close();
recoveredFile.close();
if (filesMatch) {
cout << "Исходный файл равен восстановленному." << endl;
}
else {
cout << "Исходный файл не равен восстановленному." << endl;
}
}
int main() {
setlocale(LC_ALL, "Rus");
const char* filename = "lab1.txt";
n1(filename);
n2(filename);
n3(filename);
return 0;
}