OSDN Git Service

libsensors: make the implementation be compatible with new IIO ABI
[android-x86/hardware-intel-libsensors.git] / Helpers.cpp
1 /*
2  * Copyright (C) 2008 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 <sys/types.h>
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21 #include <errno.h>
22 #include <fstream>
23 #include <iostream>
24 #include <sstream>
25 #include "Helpers.h"
26
27 int PathOps::write(const std::string &path, const std::string &buf)
28 {
29     std::string p = mBasePath + path;
30     int fd = ::open(p.c_str(), O_WRONLY);
31     if (fd < 0)
32         return -errno;
33
34     int ret = ::write(fd, buf.c_str(), buf.size());
35     close(fd);
36
37     return ret;
38 }
39
40 int PathOps::write(const std::string &path, unsigned int data)
41 {
42     std::ostringstream os;
43     os << data;
44     return PathOps::write(path, os.str());
45 }
46
47 int PathOps::read(const std::string &path, char *buf, int len)
48 {
49     std::string p = mBasePath + path;
50     int fd = ::open(p.c_str(), O_RDONLY);
51     if (fd < 0)
52         return -errno;
53
54     int ret = ::read(fd, buf, len);
55     close(fd);
56
57     return ret;
58 }
59
60 int PathOps::read(const std::string &path, std::string &buf)
61 {
62     std::string p = mBasePath + path;
63     /* Using fstream for reading stuff into std::string */
64     std::ifstream f(p.c_str(), std::fstream::in);
65     if (f.fail())
66         return -EINVAL;
67
68     int ret = 0;
69     f >> buf;
70     if (f.bad())
71         ret = -EIO;
72     f.close();
73
74     return ret;
75 }
76
77 bool PathOps::exists(const std::string &path)
78 {
79     struct stat s;
80     return (bool) (stat((mBasePath + path).c_str(), &s) == 0);
81 }
82
83 bool PathOps::exists()
84 {
85     return PathOps::exists("");
86 }