1 #include <mbgl/util/io.hpp>
2 
3 #include <cstdio>
4 #include <cerrno>
5 #include <cstring>
6 #include <iostream>
7 #include <sstream>
8 #include <fstream>
9 
10 namespace mbgl {
11 namespace util {
12 
IOException(int err,const std::string & msg)13 IOException::IOException(int err, const std::string& msg)
14     : std::runtime_error(msg + ": " + std::strerror(errno)), code(err) {
15 }
16 
write_file(const std::string & filename,const std::string & data)17 void write_file(const std::string &filename, const std::string &data) {
18     FILE *fd = fopen(filename.c_str(), "wb");
19     if (fd) {
20         fwrite(data.data(), sizeof(std::string::value_type), data.size(), fd);
21         fclose(fd);
22     } else {
23         throw std::runtime_error(std::string("Failed to open file ") + filename);
24     }
25 }
26 
read_file(const std::string & filename)27 std::string read_file(const std::string &filename) {
28     std::ifstream file(filename, std::ios::binary);
29     if (file.good()) {
30         std::stringstream data;
31         data << file.rdbuf();
32         return data.str();
33     } else {
34         throw std::runtime_error(std::string("Cannot read file ") + filename);
35     }
36 }
37 
readFile(const std::string & filename)38 optional<std::string> readFile(const std::string &filename) {
39     std::ifstream file(filename, std::ios::binary);
40     if (file.good()) {
41         std::stringstream data;
42         data << file.rdbuf();
43         return data.str();
44     }
45     return {};
46 }
47 
deleteFile(const std::string & filename)48 void deleteFile(const std::string& filename) {
49     const int ret = std::remove(filename.c_str());
50     if (ret != 0 && errno != ENOENT) {
51         throw IOException(errno, "Could not delete file " + filename);
52     }
53 }
54 
copyFile(const std::string & destination,const std::string & source)55 void copyFile(const std::string& destination, const std::string& source) {
56     std::ifstream src(source, std::ios::binary);
57     if (!src.good()) {
58         throw IOException(errno, "Cannot read file " + destination);
59     }
60     std::ofstream dst(destination, std::ios::binary);
61     if (!dst.good()) {
62         throw IOException(errno, "Cannot write file " + destination);
63     }
64     dst << src.rdbuf();
65 }
66 
67 } // namespace util
68 } // namespace mbgl
69