summaryrefslogtreecommitdiff
path: root/src/mbgl/util/io.cpp
blob: 5c385140ba3ecffb279b130c97041a41ff07cce4 (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
#include <mbgl/util/io.hpp>

#include <cstdio>
#include <cerrno>
#include <cstring>
#include <iostream>
#include <sstream>
#include <fstream>

namespace mbgl {
namespace util {

IOException::IOException(int err, const std::string& msg)
    : std::runtime_error(msg + ": " + std::strerror(errno)), code(err) {
}

void write_file(const std::string &filename, const std::string &data) {
    FILE *fd = fopen(filename.c_str(), "wbe");
    if (fd) {
        fwrite(data.data(), sizeof(std::string::value_type), data.size(), fd);
        fclose(fd);
    } else {
        throw std::runtime_error(std::string("Failed to open file ") + filename);
    }
}

std::string read_file(const std::string &filename) {
    std::ifstream file(filename, std::ios::binary);
    if (file.good()) {
        std::stringstream data;
        data << file.rdbuf();
        return data.str();
    } else {
        throw std::runtime_error(std::string("Cannot read file ") + filename);
    }
}

optional<std::string> readFile(const std::string &filename) {
    std::ifstream file(filename, std::ios::binary);
    if (file.good()) {
        std::stringstream data;
        data << file.rdbuf();
        return data.str();
    }
    return {};
}

void deleteFile(const std::string& filename) {
    const int ret = std::remove(filename.c_str());
    if (ret != 0 && errno != ENOENT) {
        throw IOException(errno, "Could not delete file " + filename);
    }
}

void copyFile(const std::string& destination, const std::string& source) {
    std::ifstream src(source, std::ios::binary);
    if (!src.good()) {
        throw IOException(errno, "Cannot read file " + source);
    }
    std::ofstream dst(destination, std::ios::binary);
    if (!dst.good()) {
        throw IOException(errno, "Cannot write file " + destination);
    }
    dst << src.rdbuf();
}

} // namespace util
} // namespace mbgl