diff --git a/src/system/Makefile.am b/src/system/Makefile.am index 63fb188f2..4944a7047 100644 --- a/src/system/Makefile.am +++ b/src/system/Makefile.am @@ -37,6 +37,7 @@ libneutrino_system_a_SOURCES = \ localize.cpp \ helpers.cpp \ ping.cpp \ + proc_tools.c \ settings.cpp \ stacktrace.cpp \ sysload.cpp \ diff --git a/src/system/proc_tools.c b/src/system/proc_tools.c new file mode 100644 index 000000000..0983de937 --- /dev/null +++ b/src/system/proc_tools.c @@ -0,0 +1,59 @@ +/* + * helper functions to interact with files, usually in the proc filesystem + * + * (C) 2012 Stefan Seyfried + * + * License: GPLv2 or later + * + */ +#include +#include +#include +#include +#include /* isspace */ +#include /* sscanf */ + +#include "proc_tools.h" + +int proc_put(const char *path, const char *value, const int len) +{ + int ret, ret2; + int pfd = open(path, O_WRONLY); + if (pfd < 0) + return pfd; + ret = write(pfd, value, len); + ret2 = close(pfd); + if (ret2 < 0) + return ret2; + return ret; +} + +int proc_get(const char *path, char *value, const int len) +{ + int ret, ret2; + int pfd = open(path, O_RDONLY); + if (pfd < 0) + return pfd; + ret = read(pfd, value, len); + value[len-1] = '\0'; /* make sure string is terminated */ + if (ret >= 0) + { + while (ret > 0 && isspace(value[ret-1])) + ret--; /* remove trailing whitespace */ + value[ret] = '\0'; /* terminate, even if ret = 0 */ + } + ret2 = close(pfd); + if (ret2 < 0) + return ret2; + return ret; +} + +unsigned int proc_get_hex(const char *path) +{ + unsigned int n, ret = 0; + char buf[16]; + n = proc_get(path, buf, 16); + if (n > 0) + sscanf(buf, "%x", &ret); + return ret; +} diff --git a/src/system/proc_tools.h b/src/system/proc_tools.h new file mode 100644 index 000000000..2a3a8cd5e --- /dev/null +++ b/src/system/proc_tools.h @@ -0,0 +1,20 @@ +/* + * helper functions to interact with files, usually in the proc filesystem + * + * (C) 2012 Stefan Seyfried + * + * License: GPLv2 or later + * + */ +#ifndef __PROC_TOOLS_H__ +#define __PROC_TOOLS_H__ +#ifdef __cplusplus +extern "C" { +#endif +int proc_put(const char *path, const char *value, const int len); +int proc_get(const char *path, char *value, const int len); +unsigned int proc_get_hex(const char *path); +#ifdef __cplusplus +} +#endif +#endif