aboutsummaryrefslogtreecommitdiff
path: root/Занимательное программирование/5/2_grey/main.cpp
blob: f4358e9cf2af2f13e6b27b2e9bead8c969fc66ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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;
}