mraa.c added internal helper functions to support globbing and link analysis
authorMichael Ring <michael.ring@swisscom.com>
Sun, 15 Feb 2015 11:47:11 +0000 (12:47 +0100)
committerBrendan Le Foll <brendan.le.foll@intel.com>
Sun, 15 Feb 2015 22:38:36 +0000 (22:38 +0000)
Signed-off-by: Michael Ring <mail@michael-ring.org>
Signed-off-by: Brendan Le Foll <brendan.le.foll@intel.com>
include/mraa_internal.h
src/mraa.c

index e2166e2..0e4c78d 100644 (file)
@@ -59,6 +59,31 @@ mraa_platform_t mraa_x86_platform();
  */
 mraa_platform_t mraa_arm_platform();
 
+/**
+* helper function to check if file exists
+*
+* @param filename to check
+* @return mraa_boolean_t boolean result.
+*/
+mraa_boolean_t mraa_file_exist(char *filename);
+
+/**
+* helper function to unglob filenames
+*
+* @param filename to unglob
+* @return char * with the existing filename matching the pattern of input. NULL if there is no match. Caller must free result
+*/
+char * mraa_file_unglob(char *filename);
+
+/**
+* helper function to find out if file that is targeted by a softlink (partially) matches the given name
+*
+* @param filename of the softlink
+* @param (partial) filename that is matched with the filename of the link-targeted file
+* @return mraa_boolean_t true when targetname (partially) matches
+*/
+mraa_boolean_t mraa_link_targets(char *filename,char *targetname);
+
 #ifdef __cplusplus
 }
 #endif
index f5b912e..e1d07d6 100644 (file)
@@ -28,6 +28,8 @@
 #include <sched.h>
 #include <string.h>
 #include <pwd.h>
+#include <glob.h>
+
 
 #include "mraa_internal.h"
 #include "gpio.h"
@@ -310,3 +312,55 @@ mraa_get_pin_count()
     }
     return plat->phy_pin_count;
 }
+
+mraa_boolean_t
+mraa_file_exist(char *filename) {
+    glob_t results;
+    results.gl_pathc = 0;
+    glob(filename, 0, NULL, &results);
+    int file_found = results.gl_pathc == 1;
+    globfree(&results);
+    return file_found;
+}
+
+char*
+mraa_file_unglob(char *filename) {
+    glob_t results;
+    char *res = NULL;
+    results.gl_pathc = 0;
+    glob(filename, 0, NULL, &results);
+    if (results.gl_pathc == 1)
+        res = strdup(results.gl_pathv[0]);
+    globfree(&results);
+    return res;
+}
+
+mraa_boolean_t
+mraa_link_targets(char *filename,char *targetname) {
+    int size = 100;
+    int nchars = 0;
+    char *buffer = NULL;
+    while (nchars == 0)
+    {
+        buffer = (char *) realloc(buffer,size);
+        if (buffer == NULL)
+            return 0;
+        nchars = readlink(filename,buffer,size);
+        if (nchars < 0 ) {
+            free(buffer);
+            return 0;
+        }
+        if (nchars >= size) {
+            size *=2;
+            nchars=0;
+        }
+    }
+    if (strstr(buffer,targetname)) {
+        free(buffer);
+        return 1;
+    }
+    else {
+        free(buffer);
+        return 0;
+    }
+}