Initial commit - move development to a public repo
[libautomation/elektra-notification.git] / lib / misplaced.c
blobd691a7bcce4c0c00aee4888e5fd4ee910282bf2d
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <string.h>
5 #include <time.h>
6 #include <unistd.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <fcntl.h>
10 #include <glob.h>
12 #include "libautomation.h"
14 char *atm_stradd(char *dest, const char *source, int *size) {
15 int len;
17 len = strlen(source);
18 if (len >= *size)
19 len = *size - 1;
20 memcpy(dest, source, len);
21 dest[len] = 0;
22 *size -= len;
24 return dest + len;
27 int atm_echo(const char *str, const char *filename) {
28 int fd, ret;
30 fd = open(filename, O_WRONLY);
31 if(fd < 0)
32 return fd;
34 ret = write(fd, str, strlen(str));
35 close(fd);
37 return ret;
40 void atm_log(const char *fmt, ...) {
41 va_list ap;
43 va_start(ap, fmt);
44 vfprintf(stderr, fmt, ap);
45 va_end(ap);
48 void atm_fail(const char *message) {
49 perror(message);
50 exit(1);
53 long int atm_read_int_or_fail(const char *str, const char *msg){
54 char *s;
55 long int res;
57 res = strtol(str, &s, 10);
58 if(s == str)
59 atm_fail(msg);
61 return res;
64 float atm_read_float_or_fail(const char *str, const char *msg){
65 char *s;
66 float res;
68 res = strtod(str, &s);
69 if(s == str)
70 atm_fail(msg);
72 return res;
76 int atm_timestamp(void) {
77 struct timespec t;
79 clock_gettime(CLOCK_BOOTTIME, &t);
81 return t.tv_sec*10 + t.tv_nsec/100000000;
84 /* Find a uniq filename to a glob pattern,
85 * useful for ever changing sysfs paths
87 char *atm_globdup(const char *pattern) {
88 glob_t globbuf;
89 char *result;
91 glob(pattern, 0, NULL, &globbuf);
92 if(globbuf.gl_pathc == 0) {
93 atm_log("WARNING: Can't match pattern '%s'", pattern);
94 result = NULL;
96 else {
97 result = strdup(*globbuf.gl_pathv);
98 if(globbuf.gl_pathc > 1)
99 atm_log("WARNING: Pattern '%s' matches multiple files. Using '%s'", pattern, result);
102 globfree(&globbuf);
104 return result;