1 /*
2 * Copyright (C) 2015 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 //#define LOG_NDEBUG 0
18 #define LOG_TAG "file"
19 #include <utils/Log.h>
20 #include "file.h"
21
22 #include <fcntl.h>
23 #include <string.h>
24 #include <unistd.h>
25
26 namespace android {
27
File()28 File::File()
29 : mInitCheck(NO_INIT),
30 mFd(-1) {
31 }
32
File(const char * path,const char * mode)33 File::File(const char *path, const char *mode)
34 : mInitCheck(NO_INIT),
35 mFd(-1) {
36 mInitCheck = setTo(path, mode);
37 }
38
~File()39 File::~File() {
40 close();
41 }
42
initCheck() const43 status_t File::initCheck() const {
44 return mInitCheck;
45 }
46
setTo(const char * path,const char * mode)47 status_t File::setTo(const char *path, const char *mode) {
48 close();
49
50 int modeval = 0;
51 if (!strcmp("r", mode)) {
52 modeval = O_RDONLY;
53 } else if (!strcmp("w", mode)) {
54 modeval = O_WRONLY | O_CREAT | O_TRUNC;
55 } else if (!strcmp("rw", mode)) {
56 modeval = O_RDWR | O_CREAT;
57 }
58
59 int filemode = 0;
60 if (modeval & O_CREAT) {
61 filemode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH;
62 }
63
64 mFd = open(path, modeval, filemode);
65
66 mInitCheck = (mFd >= 0) ? OK : -errno;
67
68 return mInitCheck;
69 }
70
close()71 void File::close() {
72 if (mFd >= 0) {
73 ::close(mFd);
74 mFd = -1;
75 }
76
77 mInitCheck = NO_INIT;
78 }
79
read(void * data,size_t size)80 ssize_t File::read(void *data, size_t size) {
81 return ::read(mFd, data, size);
82 }
83
write(const void * data,size_t size)84 ssize_t File::write(const void *data, size_t size) {
85 return ::write(mFd, data, size);
86 }
87
seekTo(off64_t pos,int whence)88 off64_t File::seekTo(off64_t pos, int whence) {
89 off64_t new_pos = lseek64(mFd, pos, whence);
90 return new_pos < 0 ? -errno : new_pos;
91 }
92
93 } // namespace android
94