1 /*
2 * Copyright (c) 2021 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 "utils/file_operation/include/file_operation.h"
17
18 #include <cstdio>
19 #include <cstdlib>
20
21 #include "utils/log/aie_log.h"
22
23 namespace OHOS {
24 namespace AI {
25 namespace {
26 const int FILE_OPERATION_SUCCESS = 0;
27 }
GetFileSize(const char * fileName,long int & fileSize)28 int GetFileSize(const char *fileName, long int &fileSize)
29 {
30 FILE *fp = fopen(fileName, "rb");
31 if (fp == nullptr) {
32 HILOGE("[FileOperation]Fopen file failed!");
33 return RETCODE_FAILURE;
34 }
35
36 if (fseek(fp, 0L, SEEK_END) != FILE_OPERATION_SUCCESS) {
37 HILOGE("[FileOperation]Fseek file failed!");
38 fclose(fp);
39 return RETCODE_FAILURE;
40 }
41
42 fileSize = ftell(fp);
43 if (fileSize <= 0) {
44 HILOGE("[FileOperation]Ftell file failed!");
45 fclose(fp);
46 return RETCODE_FAILURE;
47 }
48
49 if (fseek(fp, 0L, SEEK_SET) != FILE_OPERATION_SUCCESS) {
50 HILOGE("[FileOperation]Fseek file failed!");
51 fclose(fp);
52 return RETCODE_FAILURE;
53 }
54 int retCode = fclose(fp);
55 if (retCode != FILE_OPERATION_SUCCESS) {
56 HILOGE("[FileOperation]Fclose file failed!");
57 return RETCODE_FAILURE;
58 }
59 return RETCODE_SUCCESS;
60 }
61
ReadFile(const char * fileName,long long fileSize,long long countNumber,char * buffer)62 int ReadFile(const char *fileName, long long fileSize, long long countNumber, char *buffer)
63 {
64 if (buffer == nullptr) {
65 HILOGE("[FileOperation]Fopen file failed! Input buffer is null!");
66 return RETCODE_FAILURE;
67 }
68 FILE *fp = fopen(fileName, "rb");
69 if (fp == nullptr) {
70 HILOGE("[FileOperation]Fopen file failed!");
71 return RETCODE_FAILURE;
72 }
73
74 int readNumber = fread(buffer, fileSize, countNumber, fp);
75 if (readNumber != countNumber) {
76 HILOGE("[FileOperation]Fread file failed, readNumber is %d!", readNumber);
77 fclose(fp);
78 return RETCODE_FAILURE;
79 }
80
81 int retCode = fclose(fp);
82 if (retCode != FILE_OPERATION_SUCCESS) {
83 HILOGE("[FileOperation]Fclose file failed!");
84 return RETCODE_FAILURE;
85 }
86 return RETCODE_SUCCESS;
87 }
88 } // namespace AI
89 } // namespace OHOS