You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

file_utils.cc 2.0 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * Copyright 2019 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "common/file_utils.h"
  17. #include <climits>
  18. namespace mindspore {
  19. namespace predict {
  20. char *ReadFile(const char *file, size_t *size) {
  21. if (file == nullptr) {
  22. MS_LOGE("file is nullptr");
  23. return nullptr;
  24. }
  25. MS_ASSERT(size != nullptr);
  26. std::ifstream ifs(RealPath(file));
  27. if (!ifs.good()) {
  28. MS_LOGE("file: %s is not exist", file);
  29. return nullptr;
  30. }
  31. if (!ifs.is_open()) {
  32. MS_LOGE("file: %s open failed", file);
  33. return nullptr;
  34. }
  35. ifs.seekg(0, std::ios::end);
  36. *size = ifs.tellg();
  37. std::unique_ptr<char> buf(new (std::nothrow) char[*size]);
  38. if (buf == nullptr) {
  39. MS_LOGE("malloc buf failed, file:%s", file);
  40. ifs.close();
  41. return nullptr;
  42. }
  43. ifs.seekg(0, std::ios::beg);
  44. ifs.read(buf.get(), *size);
  45. ifs.close();
  46. return buf.release();
  47. }
  48. std::string RealPath(const char *path) {
  49. if (path == nullptr) {
  50. MS_LOGE("path is nullptr");
  51. return "";
  52. }
  53. if ((strlen(path)) >= PATH_MAX) {
  54. MS_LOGE("path is too long");
  55. return "";
  56. }
  57. std::shared_ptr<char> resolvedPath(new (std::nothrow) char[PATH_MAX]{0});
  58. if (resolvedPath == nullptr) {
  59. MS_LOGE("new resolvedPath failed");
  60. return "";
  61. }
  62. auto ret = realpath(path, resolvedPath.get());
  63. if (ret == nullptr) {
  64. MS_LOGE("realpath failed");
  65. return "";
  66. }
  67. return resolvedPath.get();
  68. }
  69. } // namespace predict
  70. } // namespace mindspore