|
15 | 15 | #include "fastdeploy/utils/utils.h" |
16 | 16 |
|
17 | 17 | #include <sstream> |
| 18 | +#include <fstream> |
| 19 | +#include <string_view> |
| 20 | + |
| 21 | +#ifdef _WIN32 |
| 22 | +#include <Windows.h> |
| 23 | +#endif |
18 | 24 |
|
19 | 25 | namespace fastdeploy { |
20 | 26 |
|
@@ -48,18 +54,53 @@ FDLogger& FDLogger::operator<<(std::ostream& (*os)(std::ostream&)) { |
48 | 54 | return *this; |
49 | 55 | } |
50 | 56 |
|
51 | | -bool ReadBinaryFromFile(const std::string& file, std::string* contents) { |
52 | | - std::ifstream fin(file, std::ios::in | std::ios::binary); |
53 | | - if (!fin.is_open()) { |
54 | | - FDERROR << "Failed to open file: " << file << " to read." << std::endl; |
| 57 | +// using os_string = std::filesystem::path::string_type; |
| 58 | +#ifdef _WIN32 |
| 59 | +using os_string = std::wstring; |
| 60 | +#else |
| 61 | +using os_string = std::string; |
| 62 | +#endif |
| 63 | + |
| 64 | +os_string to_osstring(std::string_view utf8_str) |
| 65 | +{ |
| 66 | +#ifdef _WIN32 |
| 67 | + int len = MultiByteToWideChar(CP_UTF8, 0, utf8_str.data(), (int)utf8_str.size(), nullptr, 0); |
| 68 | + os_string result(len, 0); |
| 69 | + MultiByteToWideChar(CP_UTF8, 0, utf8_str.data(), (int)utf8_str.size(), result.data(), len); |
| 70 | + return result; |
| 71 | +#else |
| 72 | + return std::string(utf8_str); |
| 73 | +#endif |
| 74 | +} |
| 75 | + |
| 76 | +bool ReadBinaryFromFile(const std::string& path, std::string* contents) |
| 77 | +{ |
| 78 | + if (!contents) { |
| 79 | + return false; |
| 80 | + } |
| 81 | + auto& result = *contents; |
| 82 | + result.clear(); |
| 83 | + |
| 84 | + std::ifstream file(to_osstring(path), std::ios::binary | std::ios::ate); |
| 85 | + if (!file.is_open()) { |
55 | 86 | return false; |
56 | 87 | } |
57 | | - fin.seekg(0, std::ios::end); |
58 | | - contents->clear(); |
59 | | - contents->resize(fin.tellg()); |
60 | | - fin.seekg(0, std::ios::beg); |
61 | | - fin.read(&(contents->at(0)), contents->size()); |
62 | | - fin.close(); |
| 88 | + |
| 89 | + auto fileSize = file.tellg(); |
| 90 | + if (fileSize != -1) { |
| 91 | + result.resize(fileSize); |
| 92 | + file.seekg(0, std::ios::beg); |
| 93 | + file.read(const_cast<char*>(result.data()), fileSize); |
| 94 | + } |
| 95 | + else { |
| 96 | + // no size available, read to EOF |
| 97 | + constexpr auto chunksize = 4096; |
| 98 | + std::string chunk(chunksize, 0); |
| 99 | + while (!file.fail()) { |
| 100 | + file.read(const_cast<char*>(chunk.data()), chunksize); |
| 101 | + result.insert(result.end(), chunk.data(), chunk.data() + file.gcount()); |
| 102 | + } |
| 103 | + } |
63 | 104 | return true; |
64 | 105 | } |
65 | 106 |
|
|
0 commit comments