1 /* 2 * I'm tired of doing "vsnprintf()" etc just to open a 3 * file, so here's a "return static buffer with printf" 4 * interface for paths. 5 * 6 * It's obviously not thread-safe. Sue me. But it's quite 7 * useful for doing things like 8 * 9 * f = open(mkpath("%s/%s.perf", base, name), O_RDONLY); 10 * 11 * which is what it's designed for. 12 */ 13 #include "cache.h" 14 15 static char bad_path[] = "/bad-path/"; 16 /* 17 * One hack: 18 */ 19 static char *get_pathname(void) 20 { 21 static char pathname_array[4][PATH_MAX]; 22 static int idx; 23 24 return pathname_array[3 & ++idx]; 25 } 26 27 static char *cleanup_path(char *path) 28 { 29 /* Clean it up */ 30 if (!memcmp(path, "./", 2)) { 31 path += 2; 32 while (*path == '/') 33 path++; 34 } 35 return path; 36 } 37 38 char *mkpath(const char *fmt, ...) 39 { 40 va_list args; 41 unsigned len; 42 char *pathname = get_pathname(); 43 44 va_start(args, fmt); 45 len = vsnprintf(pathname, PATH_MAX, fmt, args); 46 va_end(args); 47 if (len >= PATH_MAX) 48 return bad_path; 49 return cleanup_path(pathname); 50 } 51