aboutsummaryrefslogtreecommitdiff
path: root/Занимательное программирование/5/2_grey/main.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'Занимательное программирование/5/2_grey/main.cpp')
-rw-r--r--Занимательное программирование/5/2_grey/main.cpp72
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;
+}