1 /**
2 * Copyright (c) 2024 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 #include "file_util.h"
17
18 #include <fstream>
19 #include <sstream>
20
21 #include "os/filesystem.h"
22 #include "utils/logger.h"
23
24 #include "util/assert_util.h"
25
26 namespace {
27 constexpr std::string_view TAG = "[FileUtil]";
28 }
29
GetFileContent(const std::string & filePath)30 std::string panda::guard::FileUtil::GetFileContent(const std::string &filePath)
31 {
32 std::string content;
33 std::string realPath = os::GetAbsolutePath(filePath);
34 if (realPath.empty()) {
35 LOG(INFO, PANDAGUARD) << TAG << "get absolute path failed, path:" << filePath;
36 return content;
37 }
38
39 std::ifstream inputStream(realPath);
40 if (!inputStream.is_open()) {
41 LOG(INFO, PANDAGUARD) << TAG << "open real file path failed, path:" << realPath;
42 return content;
43 }
44
45 std::stringstream ss;
46 ss << inputStream.rdbuf();
47 content = ss.str();
48 inputStream.close();
49 return content;
50 }
51
GetLineDataFromFile(const std::string & filePath)52 std::vector<std::string> panda::guard::FileUtil::GetLineDataFromFile(const std::string &filePath)
53 {
54 std::vector<std::string> lineDataList;
55 std::string realPath = os::GetAbsolutePath(filePath);
56 if (realPath.empty()) {
57 LOG(INFO, PANDAGUARD) << TAG << "get absolute path failed, path:" << filePath;
58 return lineDataList;
59 }
60
61 std::ifstream inputStream(realPath);
62 if (!inputStream.is_open()) {
63 LOG(INFO, PANDAGUARD) << TAG << "open real file path failed, path:" << realPath;
64 return lineDataList;
65 }
66
67 std::string line;
68 while (std::getline(inputStream, line)) {
69 lineDataList.emplace_back(line);
70 }
71 inputStream.close();
72 return lineDataList;
73 }
74
WriteFile(const std::string & filePath,const std::string & content)75 void panda::guard::FileUtil::WriteFile(const std::string &filePath, const std::string &content)
76 {
77 std::ofstream ofs;
78 ofs.open(filePath, std::ios::trunc | std::ios::out);
79 PANDA_GUARD_ASSERT_PRINT(!ofs.is_open(), TAG, ErrorCode::GENERIC_ERROR,
80 "can not open file, invalid filePath:" << filePath);
81 ofs << content;
82 ofs.close();
83 }
84