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