1 /*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <img_utils/FileInput.h>
18
19 #include <utils/Log.h>
20
21 namespace android {
22 namespace img_utils {
23
FileInput(String8 path)24 FileInput::FileInput(String8 path) : mFp(NULL), mPath(path), mOpen(false) {}
25
~FileInput()26 FileInput::~FileInput() {
27 if (mOpen) {
28 ALOGE("%s: FileInput destroyed without calling close!", __FUNCTION__);
29 close();
30 }
31
32 }
33
open()34 status_t FileInput::open() {
35 if (mOpen) {
36 ALOGW("%s: Open called when file %s already open.", __FUNCTION__, mPath.string());
37 return OK;
38 }
39 mFp = ::fopen(mPath, "rb");
40 if (!mFp) {
41 ALOGE("%s: Could not open file %s", __FUNCTION__, mPath.string());
42 return BAD_VALUE;
43 }
44 mOpen = true;
45 return OK;
46 }
47
read(uint8_t * buf,size_t offset,size_t count)48 ssize_t FileInput::read(uint8_t* buf, size_t offset, size_t count) {
49 if (!mOpen) {
50 ALOGE("%s: Could not read file %s, file not open.", __FUNCTION__, mPath.string());
51 return BAD_VALUE;
52 }
53
54 size_t bytesRead = ::fread(buf + offset, sizeof(uint8_t), count, mFp);
55 int error = ::ferror(mFp);
56 if (error != 0) {
57 ALOGE("%s: Error %d occurred while reading file %s.", __FUNCTION__, error, mPath.string());
58 return BAD_VALUE;
59 }
60
61 // End of file reached
62 if (::feof(mFp) != 0 && bytesRead == 0) {
63 return NOT_ENOUGH_DATA;
64 }
65
66 return bytesRead;
67 }
68
close()69 status_t FileInput::close() {
70 if(!mOpen) {
71 ALOGW("%s: Close called when file %s already close.", __FUNCTION__, mPath.string());
72 return OK;
73 }
74
75 status_t ret = OK;
76 if(::fclose(mFp) != 0) {
77 ALOGE("%s: Failed to close file %s.", __FUNCTION__, mPath.string());
78 ret = BAD_VALUE;
79 }
80 mOpen = false;
81 return ret;
82 }
83
84 } /*namespace img_utils*/
85 } /*namespace android*/
86