Cleanup - 0.0.2
[libautomation.git] / lib / misplaced.c
blobefb93da39a9e5e2590a503f25d7bb795f92fdaaa
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 fputc('\n', stderr);
46 va_end(ap);
49 void atm_fail(const char *message) {
50 perror(message);
51 exit(1);
54 long int atm_read_int_or_fail(const char *str, const char *msg){
55 char *s;
56 long int res;
58 res = strtol(str, &s, 10);
59 if(s == str)
60 atm_fail(msg);
62 return res;
65 float atm_read_float_or_fail(const char *str, const char *msg){
66 char *s;
67 float res;
69 res = strtod(str, &s);
70 if(s == str)
71 atm_fail(msg);
73 return res;
77 int atm_timestamp(void) {
78 struct timespec t;
80 clock_gettime(CLOCK_BOOTTIME, &t);
82 return t.tv_sec*10 + t.tv_nsec/100000000;
85 /* Find a uniq filename to a glob pattern,
86 * useful for ever changing sysfs paths
88 char *atm_globdup(const char *pattern) {
89 glob_t globbuf;
90 char *result;
92 glob(pattern, 0, NULL, &globbuf);
93 if(globbuf.gl_pathc == 0) {
94 atm_log("WARNING: Can't match pattern '%s'", pattern);
95 result = NULL;
97 else {
98 result = strdup(*globbuf.gl_pathv);
99 if(globbuf.gl_pathc > 1)
100 atm_log("WARNING: Pattern '%s' matches multiple files. Using '%s'", pattern, result);
103 globfree(&globbuf);
105 return result;