1 /*
2 * Copyright (c) 2025 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 "security_guard_log.h"
17 #include "file_util.h"
18 #include "directory_ex.h"
19
20 namespace OHOS::Security::SecurityGuard {
21 namespace FileUtil {
ReadFileToStr(const std::string & fileName,const std::ios::pos_type fileMaxSize,std::string & str)22 bool ReadFileToStr(const std::string &fileName, const std::ios::pos_type fileMaxSize, std::string &str)
23 {
24 SGLOGI("Start read file.");
25 std::string realPath;
26 if (!PathToRealPath(fileName, realPath)) {
27 SGLOGE("Check file path failed, fileName: %{public}s", fileName.c_str());
28 return false;
29 }
30 std::ifstream stream(realPath, std::ios::in);
31 if (!stream.is_open()) {
32 SGLOGE("File stream error.");
33 return false;
34 }
35 stream.seekg(0, std::ios::end);
36 std::ios::pos_type len = stream.tellg();
37 if (len == 0 || len > fileMaxSize) {
38 SGLOGE("File is empty or too large.");
39 stream.close();
40 return false;
41 }
42 stream.seekg(0, std::ios_base::beg);
43 std::stringstream strStream;
44 strStream << stream.rdbuf();
45 str = strStream.str();
46 stream.close();
47 return true;
48 }
49 }
50 } // namespace OHOS::Security::SecurityGuard