| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | #include "file.hh" |
| 25 | |
| 26 | #include <iostream> |
| 27 | #include <fstream> |
| 28 | |
| 29 | vector<u8> read_file(const string &filename, bool binary) { |
| 30 | std::ios::openmode flags = std::ios::in |
| 31 | | std::ios::ate |
| 32 | | std::ios::binary; |
| 33 | |
| 34 | std::ifstream file(filename, flags); |
| 35 | if (!file) { |
| 36 | throw std::runtime_error("ファイルを開くに失敗: " + filename); |
| 37 | } |
| 38 | |
| 39 | auto size = file.tellg(); |
| 40 | file.clear(); |
| 41 | file.seekg(0, std::ios::beg); |
| 42 | |
| 43 | vector<u8> data(static_cast<size_t>(size)); |
| 44 | if (!file.read(reinterpret_cast<char *>(data.data()), size)) { |
| 45 | throw std::runtime_error("ファイルの読み込みに失敗。"); |
| 46 | } |
| 47 | |
| 48 | file.close(); |
| 49 | |
| 50 | return data; |
| 51 | } |
| 52 | |
| 53 | bool write_file(const string &filename, vector<string> contents, bool binary) { |
| 54 | std::ios::openmode flags; |
| 55 | if (binary) { |
| 56 | flags = std::ios::binary | std::ios::ate; |
| 57 | } else { |
| 58 | flags = std::ios::out | std::ios::trunc; |
| 59 | } |
| 60 | |
| 61 | std::ofstream file(filename, flags); |
| 62 | if (!file) { |
| 63 | throw std::runtime_error("ファイルを開くに失敗: " + filename); |
| 64 | } |
| 65 | |
| 66 | for (const auto &c : contents) { |
| 67 | file << c; |
| 68 | file << "\n"; |
| 69 | } |
| 70 | |
| 71 | file.close(); |
| 72 | |
| 73 | return true; |
| 74 | } |