1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
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 
16 #ifndef FILE_UTILS_H
17 #define FILE_UTILS_H
18 
19 #include <filesystem>
20 #include <fstream>
21 #include <iostream>
22 #include <map>
23 #include <string>
24 #include <vector>
25 
26 namespace OHOS {
27 namespace UpdateEngine {
28 constexpr int32_t FOLDER_PERMISSION = 0750;
29 
30 struct DirInfo {
31     std::string dirName;
32     int32_t dirPermissions;
33     bool isAllowDestroyContents = false; // 是否允许删除当前目录下的所有文件(包括子目录)
34 };
35 
36 class FileUtils {
37 public:
38     static bool IsFileExist(const std::string &fileName);
39     static int64_t GetFileSize(const std::string &fileName);
40     static bool IsSpaceEnough(const std::string &filePath, const int64_t requiredSpace);
41     static bool SaveDataToFile(const std::string &filePath, const std::string &data);
42     static void DeleteFile(const std::string &rootPath, bool isDeleteRootDir);
43     static bool CreateMultiDirWithPermission(const std::string &fileDir, int32_t permission);
44     static void InitAndCreateBaseDirs(const std::vector<DirInfo> &dirInfos);
45     static void DestroyBaseDirectory(const std::vector<DirInfo> &dirInfos);
46     static std::string ReadDataFromFile(const std::string &filePath);
47     static std::string GetParentDir(const std::string &fileDir);
48 
49 private:
50     static std::string GetCurrentDir(const std::string &fileDir);
51     static bool CreatDirWithPermission(const std::string &fileDir, int32_t dirPermission);
52 
53 private:
54     static std::map<std::string, int32_t> baseDirMap_;
55     static void RemoveAll(const std::filesystem::path &path);
56 };
57 } // namespace UpdateEngine
58 } // namespace OHOS
59 #endif // FILE_UTILS_H