aboutsummaryrefslogtreecommitdiff
path: root/Занимательное программирование/5/1_huffman/main.cpp
diff options
context:
space:
mode:
authorEugen Wissner <belka@caraus.de>2026-02-03 18:12:44 +0100
committerEugen Wissner <belka@caraus.de>2026-02-03 18:12:44 +0100
commit518590d59512143ff279e98aa16c9b956f4b8699 (patch)
treef78246ef362e9ad4efa874f5df60a4522de11fcf /Занимательное программирование/5/1_huffman/main.cpp
parent2499f8471ca63ad5c1a6abf21de60867e1f96289 (diff)
downloadbook-exercises-518590d59512143ff279e98aa16c9b956f4b8699.tar.gz
Добавлена первая задача пятой главы
Diffstat (limited to 'Занимательное программирование/5/1_huffman/main.cpp')
-rw-r--r--Занимательное программирование/5/1_huffman/main.cpp69
1 files changed, 69 insertions, 0 deletions
diff --git a/Занимательное программирование/5/1_huffman/main.cpp b/Занимательное программирование/5/1_huffman/main.cpp
new file mode 100644
index 0000000..24aba2c
--- /dev/null
+++ b/Занимательное программирование/5/1_huffman/main.cpp
@@ -0,0 +1,69 @@
+#include <cstring>
+#include <fstream>
+#include <vector>
+#include <cstdint>
+#include <iostream>
+#include "huffman.hpp"
+
+std::vector<std::uint8_t> read_file(char *filename)
+{
+ std::ifstream input_file{ filename, std::ios::binary | std::ios::in };
+ input_file.exceptions(std::ios::badbit | std::ios::failbit);
+
+ return std::vector<std::uint8_t>{ std::istreambuf_iterator<char>(input_file), {} };
+}
+
+enum class direction {
+ compress,
+ decompress
+};
+
+int show_usage()
+{
+ std::cerr << "Usage: huffman (compress|decompress) input_file output_file." << std::endl;
+ return 1;
+}
+
+int main(int argc, char **argv)
+{
+ direction operation;
+ if (argc != 4)
+ {
+ return show_usage();
+ }
+ if (std::strcmp(argv[1], "compress") == 0)
+ {
+ operation = direction::compress;
+ }
+ else if (std::strcmp(argv[1], "decompress") == 0)
+ {
+ operation = direction::decompress;
+ }
+ else
+ {
+ return show_usage();
+ }
+ std::vector<std::uint8_t> input;
+ try
+ {
+ input = read_file(argv[2]);
+ }
+ catch (std::iostream::failure& exception)
+ {
+ std::cerr << "Error opening file \"" << argv[2] << "\" for reading." << std::endl;
+ return 2;
+ }
+ std::ofstream output_file{ argv[3], std::ios::binary | std::ios::out | std::ios::trunc };
+ output_file.exceptions(std::ios::badbit | std::ios::failbit);
+
+ switch (operation)
+ {
+ case direction::compress:
+ compress(input, output_file);
+ break;
+ case direction::decompress:
+ decompress(input, output_file);
+ break;
+ }
+ return 0;
+}