| 127 | |
| 128 | template <typename GetDestBufferFn> |
| 129 | size_t readFileContent (const std::filesystem::path& filename, GetDestBufferFn&& getBuffer) |
| 130 | { |
| 131 | if (filename.empty()) |
| 132 | throw Error ("Illegal filename"); |
| 133 | |
| 134 | try |
| 135 | { |
| 136 | std::ifstream stream; |
| 137 | stream.exceptions (std::ofstream::failbit | std::ofstream::badbit); |
| 138 | stream.open (filename, std::ios::binary | std::ios::ate); |
| 139 | |
| 140 | if (! stream.is_open()) |
| 141 | { |
| 142 | if (! exists (filename)) |
| 143 | throw Error ("File does not exist: " + filename.string()); |
| 144 | |
| 145 | throw Error ("Failed to open file: " + filename.string()); |
| 146 | } |
| 147 | |
| 148 | auto fileSize = stream.tellg(); |
| 149 | |
| 150 | if (fileSize == 0) |
| 151 | return 0; |
| 152 | |
| 153 | if (fileSize > 0) |
| 154 | { |
| 155 | if (auto destBuffer = getBuffer (static_cast<uint64_t> (fileSize))) |
| 156 | { |
| 157 | stream.seekg (0); |
| 158 | |
| 159 | if (stream.read (static_cast<std::ifstream::char_type*> (destBuffer), static_cast<std::streamsize> (fileSize))) |
| 160 | return static_cast<size_t> (fileSize); |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | throw Error ("Failed to read from file: " + filename.string()); |
| 165 | } |
| 166 | catch (const std::ios_base::failure& e) |
| 167 | { |
| 168 | throw Error ("Failed to read from file: " + filename.string() + ": " + e.what()); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | inline std::string loadFileAsString (const std::filesystem::path& filename) |
| 173 | { |