• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (C) 2021 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 <unistd.h>
16 #include <sys/stat.h>
17 #include "util/file_utils.h"
18 using namespace std;
19 namespace OHOS {
20 namespace HiviewDFX {
FileUtils()21 FileUtils::FileUtils()
22 {
23 }
~FileUtils()24 FileUtils::~FileUtils()
25 {
26 }
27 
CreateFolder(const string & path)28 bool FileUtils::CreateFolder(const string &path)
29 {
30     if (!access(path.c_str(), F_OK) || path == "") {
31         return true;
32     }
33 
34     size_t pos = path.rfind("/");
35     if (pos == string::npos) {
36         return false;
37     }
38 
39     string upperPath = path.substr(0, pos);
40     if (CreateFolder(upperPath)) {
41         if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IRWXO)) {
42             if (errno != EEXIST) {
43                 return false;
44             }
45         }
46         return true;
47     }
48     return false;
49 }
50 
LoadStringFromProcCb(const std::string & path,bool oneLine,bool endWithoutN,const DataHandler & func)51 bool FileUtils::LoadStringFromProcCb(const std::string& path, bool oneLine, bool endWithoutN, const DataHandler& func)
52 {
53     char canonicalPath[PATH_MAX] = {0};
54     if (realpath(path.c_str(), canonicalPath) == nullptr) {
55         return false;
56     }
57     auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(canonicalPath, "re"), fclose};
58     if (fp == nullptr) {
59         return false;
60     }
61     char *lineBuf = nullptr;
62     ssize_t lineLen;
63     size_t lineAlloc = 0;
64     while ((lineLen = getline(&lineBuf, &lineAlloc, fp.get())) > 0) {
65         lineBuf[lineLen] = '\0';
66         if (endWithoutN && lineBuf[lineLen-1] == '\n') {
67             lineBuf[lineLen-1] = '\0';
68         }
69         const string content = lineBuf;
70         func(content);
71         if (oneLine) {
72             break;
73         }
74     }
75     if (lineBuf != nullptr) {
76         free(lineBuf);
77         lineBuf = nullptr;
78     }
79     return true;
80 }
81 
82 } // namespace HiviewDFX
83 } // namespace OHOS