1
2 /*
3 * Copyright (C) 2008 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 #include <stdio.h>
19 #include <string.h>
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <malloc.h>
23 #include <errno.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27
read_file(char * filename,ssize_t * _size)28 void *read_file(char *filename, ssize_t *_size)
29 {
30 int ret, fd;
31 struct stat sb;
32 ssize_t size;
33 void *buffer = NULL;
34
35 /* open the file */
36 fd = open(filename, O_RDONLY);
37 if (fd < 0)
38 return NULL;
39
40 /* find out how big it is */
41 if (fstat(fd, &sb) < 0)
42 goto bail;
43 size = sb.st_size;
44
45 /* allocate memory for it to be read into */
46 buffer = malloc(size);
47 if (!buffer)
48 goto bail;
49
50 /* slurp it into our buffer */
51 ret = read(fd, buffer, size);
52 if (ret != size)
53 goto bail;
54
55 /* let the caller know how big it is */
56 *_size = size;
57
58 bail:
59 close(fd);
60 return buffer;
61 }
truncate_sysfs_path(char * path,int num_elements_to_remove,char * buffer,int buffer_size)62 char *truncate_sysfs_path(char *path, int num_elements_to_remove, char *buffer, int buffer_size)
63 {
64 int i;
65
66 strncpy(buffer, path, buffer_size);
67
68 for (i = 0; i < num_elements_to_remove; i++) {
69 char *p = &buffer[strlen(buffer)-1];
70
71 for (p = &buffer[strlen(buffer) -1]; *p != '/'; p--);
72 *p = '\0';
73 }
74
75 return buffer;
76 }
77
read_sysfs_var(char * buffer,size_t maxlen,char * devpath,char * var)78 char *read_sysfs_var(char *buffer, size_t maxlen, char *devpath, char *var)
79 {
80 char filename[255];
81 char *p;
82 ssize_t sz;
83
84 snprintf(filename, sizeof(filename), "/sys%s/%s", devpath, var);
85 p = read_file(filename, &sz);
86 p[(strlen(p) - 1)] = '\0';
87 strncpy(buffer, p, maxlen);
88 free(p);
89 return buffer;
90 }
91
92