diff options
| author | Eugen Wissner <belka@caraus.de> | 2026-02-13 22:03:01 +0100 |
|---|---|---|
| committer | Eugen Wissner <belka@caraus.de> | 2026-02-13 22:03:01 +0100 |
| commit | 82ae29cb8a59a1e093190d14f8c5097658545a12 (patch) | |
| tree | 9ebdb8652b4cdb7a073890d018136fbf868870fd /Занимательное программирование/5/2_grey/main.cpp | |
| parent | 518590d59512143ff279e98aa16c9b956f4b8699 (diff) | |
| download | book-exercises-82ae29cb8a59a1e093190d14f8c5097658545a12.tar.gz | |
Добавлена вторая задача пятой главы
Diffstat (limited to 'Занимательное программирование/5/2_grey/main.cpp')
| -rw-r--r-- | Занимательное программирование/5/2_grey/main.cpp | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/Занимательное программирование/5/2_grey/main.cpp b/Занимательное программирование/5/2_grey/main.cpp new file mode 100644 index 0000000..f4358e9 --- /dev/null +++ b/Занимательное программирование/5/2_grey/main.cpp @@ -0,0 +1,72 @@ +#include <cstring> +#include <iostream> +#include <fstream> +#include <sstream> +#include "grey.hpp" +#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), {} }; +} + +int show_usage() +{ + std::cerr << "Usage: grey (compress|decompress) input_file output_file." << std::endl; + return 1; +} + +enum class direction { + compress, + decompress +}; + +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(); + } + switch (operation) + { + case direction::compress: + try { + std::ofstream output_file{ argv[3], std::ios::binary | std::ios::out | std::ios::trunc }; + output_file.exceptions(std::ios::badbit | std::ios::failbit); + + auto rle_stream = to_rle(argv[2]); + compress(rle_stream, output_file); + break; + } + catch (const std::runtime_error& e) + { + std::cerr << "Error decoding \"" << argv[2] << "\": " << e.what() << '.' << std::endl; + return 2; + } + case direction::decompress: + { + auto input = read_file(argv[2]); + std::stringstream rle_stream; + decompress(input, rle_stream); + from_rle(rle_stream.str(), argv[3]); + } + break; + } + return 0; +} |
