CCF
Loading...
Searching...
No Matches
files.h
Go to the documentation of this file.
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the Apache 2.0 License.
3#pragma once
4
5#include <cstring>
6#include <fstream>
7#include <glob.h>
8#include <iostream>
9#include <nlohmann/json.hpp>
10#include <optional>
11#include <sstream>
12#include <string>
13#include <vector>
14
15#define FMT_HEADER_ONLY
16#include <fmt/format.h>
17#include <fmt/ostream.h>
18
19namespace files
20{
21 namespace fs = std::filesystem;
22
29 static bool exists(const std::string& file)
30 {
31 std::ifstream f(file.c_str());
32 return f.good();
33 }
34
43 static std::vector<uint8_t> slurp(
44 const std::string& file, bool optional = false)
45 {
46 std::ifstream f(file, std::ios::binary | std::ios::ate);
47
48 if (!f)
49 {
50 if (optional)
51 {
52 return {};
53 }
54 else
55 {
56 std::cerr << "Could not open file " << file << std::endl;
57 exit(-1);
58 }
59 }
60
61 auto size = f.tellg();
62 f.seekg(0, std::ios::beg);
63
64 std::vector<uint8_t> data(size);
65 f.read((char*)data.data(), size);
66
67 if (!optional && !f)
68 {
69 std::cerr << "Could not read file " << file << std::endl;
70 exit(-1);
71 }
72 return data;
73 }
74
83 static std::string slurp_string(
84 const std::string& file, bool optional = false)
85 {
86 auto v = slurp(file, optional);
87 return {v.begin(), v.end()};
88 }
89
90 static std::optional<std::string> try_slurp_string(const std::string& file)
91 {
92 if (!fs::exists(file))
93 {
94 return std::nullopt;
95 }
96 return files::slurp_string(file);
97 }
98
108 static nlohmann::json slurp_json(
109 const std::string& file, bool optional = false)
110 {
111 auto v = slurp(file, optional);
112 if (v.size() == 0)
113 return nlohmann::json();
114
115 return nlohmann::json::parse(v.begin(), v.end());
116 }
117
124 static void dump(const std::vector<uint8_t>& data, const std::string& file)
125 {
126 using namespace std;
127 ofstream f(file, ios::binary | ios::trunc);
128 f.write((char*)data.data(), data.size());
129 if (!f)
130 throw logic_error("Failed to write to file: " + file);
131 }
132
139 static void dump(const std::string& data, const std::string& file)
140 {
141 return dump(std::vector<uint8_t>(data.begin(), data.end()), file);
142 }
143
144 static void rename(const fs::path& src, const fs::path& dst)
145 {
146 std::error_code ec;
147 fs::rename(src, dst, ec);
148 if (ec)
149 {
150 throw std::logic_error(fmt::format(
151 "Could not rename file {} to {}: {}",
152 src.string(),
153 dst.string(),
154 ec.message()));
155 }
156 }
157
158 static void create_directory(const fs::path& dir)
159 {
160 std::error_code ec;
161 fs::create_directory(dir, ec);
162 if (ec && ec != std::errc::file_exists)
163 {
164 throw std::logic_error(fmt::format(
165 "Could not create directory {}: {}", dir.string(), ec.message()));
166 }
167 }
168}
Definition files.h:20
STL namespace.