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