• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <climits>
17 #include "base/utils/utils.h"
18 #ifdef WINDOWS_PLATFORM
19 #include <shlwapi.h>
20 #endif
21 namespace OHOS::Ace {
22 constexpr int64_t MAX_FILE_SIZE = 20 * 1024 * 1024;
RealPath(const std::string & fileName,char * realPath)23     bool RealPath(const std::string& fileName, char* realPath)
24 {
25 #if defined(WINDOWS_PLATFORM)
26         return PathCanonicalize(realPath, fileName.c_str()) != 0;
27 #else
28         return realpath(fileName.c_str(), realPath) != nullptr;
29 #endif
30 }
31 
RoundToMaxPrecision(double value)32 double RoundToMaxPrecision(double value)
33 {
34     int precision = std::numeric_limits<double>::digits10;
35     double factor = std::pow(10, precision - 2);
36     if (NearZero(factor)) {
37         return value;
38     }
39     return std::round(value * factor) / factor;
40 }
41 
ReadFileToString(const std::string & packagePathStr,const std::string & fileName)42 std::string ReadFileToString(const std::string& packagePathStr, const std::string& fileName)
43 {
44     auto configPath = packagePathStr + fileName;
45     char realPath[PATH_MAX] = { 0x00 };
46     if (!RealPath(configPath.c_str(), realPath)) {
47         LOGE("realpath fail!");
48         return "";
49     }
50     std::unique_ptr<FILE, decltype(&fclose)> file(fopen(realPath, "rb"), fclose);
51     if (!file) {
52         LOGE("open file failed");
53         return "";
54     }
55     if (std::fseek(file.get(), 0, SEEK_END) != 0) {
56         LOGE("seek file tail error");
57         return "";
58     }
59 
60     int64_t size = std::ftell(file.get());
61     if (size == -1L || size <= 0L || size > MAX_FILE_SIZE) {
62         return "";
63     }
64 
65     char* fileData = new (std::nothrow) char[size + 1];
66     if (fileData == nullptr) {
67         return "";
68     }
69 
70     rewind(file.get());
71     std::unique_ptr<char[]> jsonStream(fileData);
72     size_t result = std::fread(jsonStream.get(), 1, size, file.get());
73     jsonStream[size] = '\0';
74     if (result != static_cast<size_t>(size)) {
75         LOGE("read file failed");
76         return "";
77     }
78 
79     return fileData;
80 }
81 }