io_utils.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /* Copyright 2019-2020 Canaan Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. #pragma once
  16. #include <boost/filesystem.hpp>
  17. #include <fstream>
  18. #include <vector>
  19. namespace nncase
  20. {
  21. inline std::vector<uint8_t> read_file(const boost::filesystem::path &filename)
  22. {
  23. std::ifstream infile(filename.c_str(), std::ios::binary | std::ios::in);
  24. if (!infile.good())
  25. throw std::runtime_error("Cannot open file: " + filename.string());
  26. infile.seekg(0, std::ios::end);
  27. size_t length = infile.tellg();
  28. if (!length)
  29. throw std::runtime_error("Invalid file: " + filename.string());
  30. infile.seekg(0, std::ios::beg);
  31. std::vector<uint8_t> data(length);
  32. infile.read(reinterpret_cast<char *>(data.data()), length);
  33. infile.close();
  34. return data;
  35. }
  36. }