| 38 | |
| 39 | template <typename T> |
| 40 | inline T readFile(boost::filesystem::path const& _file) |
| 41 | { |
| 42 | assertThrow(boost::filesystem::exists(_file), FileNotFound, _file.string()); |
| 43 | |
| 44 | // ifstream does not always fail when the path leads to a directory. Instead it might succeed |
| 45 | // with tellg() returning a nonsensical value so that std::length_error gets raised in resize(). |
| 46 | assertThrow(boost::filesystem::is_regular_file(_file), NotAFile, _file.string()); |
| 47 | |
| 48 | T ret; |
| 49 | size_t const c_elementSize = sizeof(typename T::value_type); |
| 50 | std::ifstream is(_file.string(), std::ifstream::binary); |
| 51 | |
| 52 | // Technically, this can still fail even though we checked above because FS content can change at any time. |
| 53 | assertThrow(is, FileNotFound, _file.string()); |
| 54 | |
| 55 | // get length of file: |
| 56 | is.seekg(0, is.end); |
| 57 | std::streamoff length = is.tellg(); |
| 58 | if (length == 0) |
| 59 | return ret; // do not read empty file (MSVC does not like it) |
| 60 | is.seekg(0, is.beg); |
| 61 | |
| 62 | ret.resize((static_cast<size_t>(length) + c_elementSize - 1) / c_elementSize); |
| 63 | is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), static_cast<std::streamsize>(length)); |
| 64 | return ret; |
| 65 | } |
| 66 | |
| 67 | } |
| 68 | |