aboutsummaryrefslogtreecommitdiff
path: root/Занимательное программирование/5/1_huffman/main.cpp
blob: 24aba2c95b4983aed30ff6055b06900684992580 (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
#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;
}