blob: 498e7153d47ae73c307aed49d463d48cbd6c1291 [file] [log] [blame]
Ruben Brunke5077212014-04-28 16:39:12 -07001/*
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
21namespace android {
22namespace img_utils {
23
24FileInput::FileInput(String8 path) : mFp(NULL), mPath(path), mOpen(false) {}
25
26FileInput::~FileInput() {
27 if (mOpen) {
28 ALOGE("%s: FileInput destroyed without calling close!", __FUNCTION__);
29 close();
30 }
31
32}
33
34status_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
Ruben Brunk4510de22014-05-28 18:42:37 -070048ssize_t FileInput::read(uint8_t* buf, size_t offset, size_t count) {
Ruben Brunke5077212014-04-28 16:39:12 -070049 if (!mOpen) {
50 ALOGE("%s: Could not read file %s, file not open.", __FUNCTION__, mPath.string());
Ruben Brunk4510de22014-05-28 18:42:37 -070051 return BAD_VALUE;
Ruben Brunke5077212014-04-28 16:39:12 -070052 }
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());
Ruben Brunk4510de22014-05-28 18:42:37 -070058 return BAD_VALUE;
Ruben Brunke5077212014-04-28 16:39:12 -070059 }
Ruben Brunk4510de22014-05-28 18:42:37 -070060
61 // End of file reached
62 if (::feof(mFp) != 0 && bytesRead == 0) {
63 return NOT_ENOUGH_DATA;
64 }
65
Ruben Brunke5077212014-04-28 16:39:12 -070066 return bytesRead;
67}
68
69status_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 OK;
82}
83
84} /*namespace img_utils*/
85} /*namespace android*/