FileInput.cpp revision e507721000647a7d8afe44c63ef7fd04ef8971b1
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
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
48size_t FileInput::read(uint8_t* buf, size_t offset, size_t count, status_t* err) {
49    if (!mOpen) {
50        ALOGE("%s: Could not read file %s, file not open.", __FUNCTION__, mPath.string());
51        if (err != NULL) *err = BAD_VALUE;
52        return 0;
53    }
54
55    size_t bytesRead = ::fread(buf + offset, sizeof(uint8_t), count, mFp);
56    int error = ::ferror(mFp);
57    if (error != 0) {
58        ALOGE("%s: Error %d occurred while reading file %s.", __FUNCTION__, error, mPath.string());
59        if (err != NULL) *err = BAD_VALUE;
60    }
61    return bytesRead;
62}
63
64status_t FileInput::close() {
65    if(!mOpen) {
66        ALOGW("%s: Close called when file %s already close.", __FUNCTION__, mPath.string());
67        return OK;
68    }
69
70    status_t ret = OK;
71    if(::fclose(mFp) != 0) {
72        ALOGE("%s: Failed to close file %s.", __FUNCTION__, mPath.string());
73        ret = BAD_VALUE;
74    }
75    mOpen = false;
76    return OK;
77}
78
79} /*namespace img_utils*/
80} /*namespace android*/
81