libs/io/src/eu/io/file.cc
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include "eu/io/file.h" | ||
| 2 | |||
| 3 | #include <fstream> | ||
| 4 | |||
| 5 | namespace eu::io | ||
| 6 | { | ||
| 7 | |||
| 8 | template<typename TChar> | ||
| 9 | ✗ | std::basic_string<TChar> tstring_from_stream(std::basic_istream<TChar>& handle) | |
| 10 | { | ||
| 11 | // https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring/2602258 | ||
| 12 | ✗ | std::basic_string<TChar> line; | |
| 13 | ✗ | std::basic_ostringstream<TChar> ss; | |
| 14 | ✗ | while (std::getline(handle, line)) | |
| 15 | { | ||
| 16 | ✗ | ss << line << '\n'; | |
| 17 | } | ||
| 18 | ✗ | return ss.str(); | |
| 19 | ✗ | } | |
| 20 | |||
| 21 | template<typename TChar> | ||
| 22 | ✗ | std::basic_string<TChar> tstring_from_file(const std::string& path, std::basic_string<TChar> err) | |
| 23 | { | ||
| 24 | ✗ | std::basic_ifstream<TChar> handle(path); | |
| 25 | ✗ | if (handle.good() == false) | |
| 26 | { | ||
| 27 | ✗ | LOG_ERR("Unable to open file '{}'", path); | |
| 28 | ✗ | return err; | |
| 29 | } | ||
| 30 | |||
| 31 | ✗ | return tstring_from_stream<TChar>(handle); | |
| 32 | ✗ | } | |
| 33 | |||
| 34 | ✗ | std::string string_from_file(const std::string& path) | |
| 35 | { | ||
| 36 | ✗ | return tstring_from_file<char>(path, ""); | |
| 37 | } | ||
| 38 | |||
| 39 | ✗ | std::vector<uint8_t> bytes_from_file(const std::string& path) | |
| 40 | { | ||
| 41 | ✗ | std::ifstream stream(path, std::ios::in | std::ios::binary); | |
| 42 | ✗ | if (stream.good() == false) | |
| 43 | { | ||
| 44 | ✗ | LOG_ERR("Unable to open file '{}'", path); | |
| 45 | ✗ | return {}; | |
| 46 | } | ||
| 47 | ✗ | std::vector<uint8_t> contents((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>()); | |
| 48 | ✗ | return contents; | |
| 49 | ✗ | } | |
| 50 | |||
| 51 | |||
| 52 | } | ||
| 53 |