master
ブランチ master
cpputils / src / util / file.cc
2.2 KB、75行 生 Blame 履歴
1/*
2# 076 Free License
3
4Copyright (c) テクニカル諏訪子
5
6Permission is hereby granted to any person obtaining a copy of the software
7C++ Utils (the "Software") to use, modify, merge, copy, publish, distribute,
8sublicense, and/or sell copies of the Software, subject to the following conditions:
9
10 1. **Origin Attribution**:
11 - You must not misrepresent the origin of the Software; you must not claim
12 you created the original Software.
13 2. **Notice Preservation**:
14 - This license and the above copyright notice must remain intact in all copies
15 of the source code.
16
17THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
19PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
21CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
22OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23*/
24#include <util/file.hh>
25
26#include <iostream>
27#include <fstream>
28
29vector<u8> read_file(const string &filename, bool binary) {
30 std::ios::openmode flags;
31 if (binary) {
32 flags = std::ios::binary | std::ios::ate;
33 } else {
34 flags = std::ios::in;
35 }
36
37 std::ifstream file(filename, flags);
38 if (!file) {
39 throw std::runtime_error("ファイルを開くに失敗: " + filename);
40 }
41
42 const auto size = file.tellg();
43 file.seekg(0);
44 vector<u8> data(static_cast<size_t>(size));
45 if (!file.read(reinterpret_cast<char *>(data.data()), size)) {
46 throw std::runtime_error("ファイルの読み込みに失敗。");
47 }
48
49 file.close();
50
51 return data;
52}
53
54bool write_file(const string &filename, vector<string> contents, bool binary) {
55 std::ios::openmode flags;
56 if (binary) {
57 flags = std::ios::binary | std::ios::ate;
58 } else {
59 flags = std::ios::out | std::ios::trunc;
60 }
61
62 std::ofstream file(filename, flags);
63 if (!file) {
64 throw std::runtime_error("ファイルを開くに失敗: " + filename);
65 }
66
67 for (const auto &c : contents) {
68 file << c;
69 file << "\n";
70 }
71
72 file.close();
73
74 return true;
75}