| 1 | #define CPP_UTILITIES_IOMISC_STRING_VIEW |
| 2 | |
| 3 | #include "./misc.h" |
| 4 | #include "./nativefilestream.h" |
| 5 | |
| 6 | #include <iterator> |
| 7 | |
| 8 | using namespace std; |
| 9 | |
| 10 | namespace CppUtilities { |
| 11 | |
| 12 | /*! |
| 13 | * \brief Reads all contents of the specified file in a single call. |
| 14 | * \throws Throws std::ios_base::failure when an error occurs or the specified \a maxSize |
| 15 | * would be exceeded. |
| 16 | */ |
| 17 | std::string readFile(const std::string &path, std::string::size_type maxSize) |
| 18 | { |
| 19 | auto file = NativeFileStream(); |
| 20 | file.exceptions(ios_base::failbit | ios_base::badbit); |
| 21 | file.open(path, ios_base::in | ios_base::binary); |
| 22 | file.seekg(0, ios_base::end); |
| 23 | string res; |
| 24 | const auto size = static_cast<string::size_type>(file.tellg()); |
| 25 | if (maxSize != string::npos && size > maxSize) { |
| 26 | throw ios_base::failure("File exceeds max size"); |
| 27 | } |
| 28 | res.reserve(size); |
| 29 | file.seekg(ios_base::beg); |
| 30 | // ignore warning about null pointer dereference from GCC 12 for now (which is *likely* not correct) |
| 31 | #ifdef __GNUC__ |
| 32 | #pragma GCC diagnostic push |
| 33 | #pragma GCC diagnostic ignored "-Wnull-dereference" |
| 34 | #endif |
| 35 | res.assign((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); |
| 36 | #ifdef __GNUC__ |
| 37 | #pragma GCC diagnostic pop |
| 38 | #endif |
| 39 | return res; |
| 40 | } |
| 41 | |
| 42 | /*! |
| 43 | * \brief Reads all contents of the specified file in a single call. |
| 44 | * \throws Throws std::ios_base::failure when an error occurs or the specified \a maxSize |
| 45 | * would be exceeded. |
| 46 | */ |
| 47 | std::string readFile(std::string_view path, std::string_view::size_type maxSize) |
| 48 | { |
| 49 | return readFile(std::string(path), maxSize); |
| 50 | } |
| 51 | |
| 52 | /*! |
| 53 | * \brief Writes all \a contents to the specified file in a single call. |
| 54 | * \throws Throws std::ios_base::failure when an error occurs. |
| 55 | * \remarks Closing the file manually to prevent flushing the file within the d'tor which |
| 56 | * would suppress an exception |
| 57 | */ |
| 58 | void writeFile(std::string_view path, std::string_view contents) |
| 59 | { |
| 60 | auto file = NativeFileStream(); |
| 61 | file.exceptions(ios_base::failbit | ios_base::badbit); |
| 62 | file.open(std::string(path), ios_base::out | ios_base::trunc | ios_base::binary); |
| 63 | file.write(contents.data(), static_cast<std::streamoff>(contents.size())); |
| 64 | file.close(); |
| 65 | } |
| 66 | |
| 67 | } // namespace CppUtilities |