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_UTIL_H
17 #define FILE_UTIL_H
18 
19 #include <fstream>
20 #include <algorithm>
21 #include <string>
22 
23 namespace OHOS {
24 namespace HiviewDFX {
25 namespace {
26 const int MAX_FILE_LENGTH = 32 * 1024 * 1024;
27 }
28 
LoadStringFromFile(const std::string& filePath, std::string& content)29 static bool LoadStringFromFile(const std::string& filePath, std::string& content)
30 {
31     std::ifstream file(filePath.c_str());
32     if (!file.is_open()) {
33         return false;
34     }
35 
36     file.seekg(0, std::ios::end);
37     const long fileLength = file.tellg();
38     if (fileLength > MAX_FILE_LENGTH) {
39         return false;
40     }
41 
42     content.clear();
43     file.seekg(0, std::ios::beg);
44     std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), std::back_inserter(content));
45     return true;
46 }
47 } // namespace HiviewDFX
48 } // namespace OHOS
49 #endif
50