syshelpers.h
1 /*
2  * This file (syshelpers.h) is part of h4r_ev3_control.
3  * Date: 22.11.2015
4  *
5  * Author: Christian Holl
6  * http://github.com/Hacks4ROS
7  *
8  * h4r_ev3_control is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * h4r_ev3_control is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with ev3_control. If not, see <http://www.gnu.org/licenses/>.
20  *
21  */
22 #ifndef SYSHELPERS_H_
23 #define SYSHELPERS_H_
24 
25 
26 #include <string>
27 #include <map>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <stdio.h>
31 #include <dirent.h>
32 
33 #include <h4r_ev3_control/FixedBuffer.h>
34 #include <h4r_ev3_control/StringEnum.h>
35 
36 namespace ev3_control
37 {
38 
42 typedef FixedBuffer::FixedBuffer<256> FileNameBuffer;
43 
49 bool pathExists(const char* path);
50 
51 
58 bool writeIntToSysFile(FILE *fileptr,int value);
59 
66 bool readIntFromSysFile(FILE *fileptr, int &value);
67 
75 template <typename T>
76 bool writeKeyToSysFile(FILE *fileptr, const StringEnum<T> &strmap, T key)
77 {
78 
79  char outbuf[256];
80  int len=strlen(strmap[key]);
81  strncpy(outbuf, strmap[key], len);
82 
83  int wrote=fwrite(outbuf,1,len,fileptr);
84 
85  if(fflush(fileptr))
86  return false;
87  rewind(fileptr);
88 
89  return wrote==len;
90 }
91 
99 template <typename T>
100 bool readKeyFromSysFile(FILE *fileptr,const StringEnum<T> &strmap, T &value)
101 {
102  fflush(fileptr);
103  rewind(fileptr);
104  int64_t value_out;
105 
106  char buffer[256];
107  char *buf=&buffer[0];
108  char **bufptr=&buf;
109 
110  bool negative;
111  ssize_t read;
112  size_t len=256;
113  int l=0;
114  bool ok=false;
115  while ((read = getline(bufptr, &len, fileptr)) != -1) {
116  if(l==0)
117  {
118  buffer[read-1]=0x00;//remove linefeed!
119  value=strmap[buffer];
120  if(value<0)
121  {
122  return false;
123  }
124  else
125  {
126  ok=true;
127  }
128 
129  }
130  else
131  {
132  if(l!=1 || read!=1)
133  {
134  return false;
135  }
136  }
137 
138  return ok;
139  }
140 
141 
142  fscanf(fileptr,"%[^\n]",buffer);
143  return true;
144 }
145 
155 bool matchFileContentInEqualSubdirectories(const char* parent,
156  const char* file,
157  const char* content,
158  FileNameBuffer &match_dir);
159 
160 } /*ev3_control*/
161 #endif /* SYSHELPERS_H_ */