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#include "file_util.h"
16
17#include <dirent.h>
18#include <fstream>
19#include <iostream>
20#include <sys/stat.h>
21#include <sys/types.h>
22#include <unistd.h>
23
24namespace OHOS {
25namespace HiviewDFX {
26namespace FileUtil {
27namespace {
28const char PATH_DELIMITER = '/';
29}
30bool IsFileExists(const std::string& file)
31{
32    return access(file.c_str(), F_OK) == 0;
33}
34
35bool IsFile(const std::string& file)
36{
37    struct stat statBuf {};
38    return lstat(file.c_str(), &statBuf) == 0 ? S_ISREG(statBuf.st_mode) : false;
39}
40
41bool IsDirectory(const std::string& dir)
42{
43    struct stat statBuf {};
44    return lstat(dir.c_str(), &statBuf) == 0 ? S_ISDIR(statBuf.st_mode) : false;
45}
46
47bool RemoveFile(const std::string& file)
48{
49    return !IsFileExists(file) || (remove(file.c_str()) == 0);
50}
51
52bool RemoveDirectory(const std::string& dir)
53{
54    return !IsFileExists(dir) || (rmdir(dir.c_str()) == 0);
55}
56
57bool ForceCreateDirectory(const std::string& dir)
58{
59    std::string::size_type index = 0;
60    do {
61        std::string subPath;
62        index = dir.find('/', index + 1); // (index + 1) means the next char traversed
63        if (index == std::string::npos) {
64            subPath = dir;
65        } else {
66            subPath = dir.substr(0, index);
67        }
68
69        if (!IsFileExists(subPath) && mkdir(subPath.c_str(), S_IRWXU) != 0) {
70            return false;
71        }
72    } while (index != std::string::npos);
73    return IsFileExists(dir);
74}
75
76std::string GetFilePathByDir(const std::string& dir, const std::string& fileName)
77{
78    if (dir.empty()) {
79        return fileName;
80    }
81    std::string filePath = dir;
82    if (filePath.back() != '/') {
83        filePath.push_back(PATH_DELIMITER);
84    }
85    filePath.append(fileName);
86    return filePath;
87}
88
89bool IsLegalPath(const std::string& path)
90{
91    if (path.find("./") != std::string::npos ||
92        path.find("../") != std::string::npos) {
93        return false;
94    }
95    return true;
96}
97} // namespace FileUtil
98} // namespace HiviewDFX
99} // namespace OHOS
100