utils.cpp 1.5 KB
Newer Older
gabime's avatar
gabime committed
1 2 3 4
#include "includes.h"

void prepare_logdir()
{
gabime's avatar
gabime committed
5
    spdlog::drop_all();
gabime's avatar
gabime committed
6
#ifdef _WIN32
gabime's avatar
gabime committed
7
    system("if not exist logs mkdir logs");
8
    system("del /F /Q logs\\*");
gabime's avatar
gabime committed
9
#else
gabime's avatar
gabime committed
10
    auto rv = system("mkdir -p logs");
gabime's avatar
gabime committed
11
    if (rv != 0)
12 13 14
    {
        throw std::runtime_error("Failed to mkdir -p logs");
    }
gabime's avatar
gabime committed
15
    rv = system("rm -f logs/*");
gabime's avatar
gabime committed
16
    if (rv != 0)
17 18 19
    {
        throw std::runtime_error("Failed to rm -f logs/*");
    }
gabime's avatar
gabime committed
20
#endif
gabime's avatar
gabime committed
21 22
}

gabime's avatar
gabime committed
23
std::string file_contents(const std::string &filename)
gabime's avatar
gabime committed
24 25 26
{
    std::ifstream ifs(filename);
    if (!ifs)
27
    {
gabime's avatar
gabime committed
28
        throw std::runtime_error("Failed open file ");
29
    }
gabime's avatar
gabime committed
30
    return std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
gabime's avatar
gabime committed
31 32
}

gabime's avatar
gabime committed
33
std::size_t count_lines(const std::string &filename)
gabime's avatar
gabime committed
34 35 36
{
    std::ifstream ifs(filename);
    if (!ifs)
37
    {
gabime's avatar
gabime committed
38
        throw std::runtime_error("Failed open file ");
39
    }
gabime's avatar
gabime committed
40 41 42

    std::string line;
    size_t counter = 0;
gabime's avatar
gabime committed
43
    while (std::getline(ifs, line))
gabime's avatar
gabime committed
44 45 46 47
        counter++;
    return counter;
}

gabime's avatar
gabime committed
48
std::size_t get_filesize(const std::string &filename)
gabime's avatar
gabime committed
49 50 51
{
    std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary);
    if (!ifs)
52
    {
gabime's avatar
gabime committed
53
        throw std::runtime_error("Failed open file ");
54
    }
gabime's avatar
gabime committed
55

56
    return static_cast<std::size_t>(ifs.tellg());
gabime's avatar
gabime committed
57
}
58 59

// source: https://stackoverflow.com/a/2072890/192001
gabime's avatar
gabime committed
60
bool ends_with(std::string const &value, std::string const &ending)
gabime's avatar
gabime committed
61
{
gabime's avatar
gabime committed
62
    if (ending.size() > value.size())
63
    {
gabime's avatar
gabime committed
64
        return false;
65
    }
gabime's avatar
gabime committed
66
    return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
67
}