util.c (1486B)
1 /* See LICENSE file for copyright and license details. */ 2 3 #include <errno.h> 4 #include <stdarg.h> 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <string.h> 8 #include <sys/stat.h> 9 10 #include "util.h" 11 12 void 13 die(const char *fmt, ...) 14 { 15 va_list ap; 16 17 va_start(ap, fmt); 18 fprintf(stderr, "sframe: "); 19 vfprintf(stderr, fmt, ap); 20 if (fmt[0] && fmt[strlen(fmt) - 1] == ':') { 21 fprintf(stderr, " %s", strerror(errno)); 22 } 23 fprintf(stderr, "\n"); 24 va_end(ap); 25 exit(1); 26 } 27 28 void 29 warn(const char *fmt, ...) 30 { 31 va_list ap; 32 33 va_start(ap, fmt); 34 fprintf(stderr, "sframe: "); 35 vfprintf(stderr, fmt, ap); 36 if (fmt[0] && fmt[strlen(fmt) - 1] == ':') { 37 fprintf(stderr, " %s", strerror(errno)); 38 } 39 fprintf(stderr, "\n"); 40 va_end(ap); 41 } 42 43 void * 44 ecalloc(size_t nmemb, size_t size) 45 { 46 void *p; 47 48 p = calloc(nmemb, size); 49 if (!p) 50 die("calloc:"); 51 return p; 52 } 53 54 void * 55 emalloc(size_t size) 56 { 57 void *p; 58 59 p = malloc(size); 60 if (!p) 61 die("malloc:"); 62 return p; 63 } 64 65 char * 66 estrdup(const char *s) 67 { 68 char *p; 69 70 p = strdup(s); 71 if (!p) 72 die("strdup:"); 73 return p; 74 } 75 76 /* mkdir -p: create all components of path */ 77 int 78 mkdirp(const char *path) 79 { 80 char buf[4096]; 81 char *p; 82 size_t len; 83 84 len = strlen(path); 85 if (len == 0 || len >= sizeof(buf)) 86 return -1; 87 88 memcpy(buf, path, len + 1); 89 90 for (p = buf + 1; *p; p++) { 91 if (*p == '/') { 92 *p = '\0'; 93 if (mkdir(buf, 0755) < 0 && errno != EEXIST) 94 return -1; 95 *p = '/'; 96 } 97 } 98 if (mkdir(buf, 0755) < 0 && errno != EEXIST) 99 return -1; 100 101 return 0; 102 }