1 /**
2 * Copyright 2021-2023 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
17 #ifndef MINDSPORE_CORE_UTILS_FILE_UTILS_H_
18 #define MINDSPORE_CORE_UTILS_FILE_UTILS_H_
19
20 #include <sys/stat.h>
21 #include <string>
22 #include <fstream>
23 #include <optional>
24 #include "mindspore/core/utils/ms_utils.h"
25 #include "mindapi/base/macros.h"
26 #include "utils/log_adapter.h"
27 #include "utils/os.h"
28
29 namespace mindspore {
30 class MS_CORE_API FileUtils {
31 public:
32 FileUtils() = default;
33 ~FileUtils() = default;
34
35 static std::fstream *OpenFile(const std::string &file_path, std::ios_base::openmode open_mode);
36 static bool ParserPathAndModelName(const std::string &output_path, std::string *save_path, std::string *model_name);
37
38 static std::optional<std::string> GetRealPath(const char *path);
39 static void SplitDirAndFileName(const std::string &path, std::optional<std::string> *prefix_path,
40 std::optional<std::string> *file_name);
41 static void ConcatDirAndFileName(const std::optional<std::string> *dir, const std::optional<std::string> *file_name,
42 std::optional<std::string> *path);
43 static std::optional<std::string> CreateNotExistDirs(const std::string &path,
44 const bool support_relative_path = false);
45 #if defined(_WIN32) || defined(_WIN64)
46 static std::string GB2312ToUTF_8(const char *gb2312);
47 static std::string UTF_8ToGB2312(const char *text);
48 #endif
49 };
50
ChangeFileMode(const std::string & file_name,mode_t mode)51 static inline void ChangeFileMode(const std::string &file_name, mode_t mode) {
52 if (access(file_name.c_str(), F_OK) == -1) {
53 return;
54 }
55 try {
56 if (chmod(common::SafeCStr(file_name), mode) != 0) {
57 MS_LOG(WARNING) << "Change file `" << file_name << "` to mode " << std::oct << mode << " fail.";
58 }
59 } catch (std::exception &e) {
60 MS_LOG(WARNING) << "File `" << file_name << "` change mode failed! May be not exist.";
61 }
62 }
63 } // namespace mindspore
64 #endif // MINDSPORE_CORE_UTILS_FILE_UTILS_H_
65