Ingo Molnar | 0780060 | 2009-04-20 15:00:56 +0200 | [diff] [blame] | 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" |
Arnaldo Carvalho de Melo | 175729f | 2016-07-07 11:38:09 -0300 | [diff] [blame] | 14 | #include "util.h" |
| 15 | #include <limits.h> |
Ingo Molnar | 0780060 | 2009-04-20 15:00:56 +0200 | [diff] [blame] | 16 | |
| 17 | static char bad_path[] = "/bad-path/"; |
| 18 | /* |
Arnaldo Carvalho de Melo | 814b3f5 | 2016-06-16 17:10:46 -0300 | [diff] [blame] | 19 | * One hack: |
Ingo Molnar | 0780060 | 2009-04-20 15:00:56 +0200 | [diff] [blame] | 20 | */ |
Ingo Molnar | 0780060 | 2009-04-20 15:00:56 +0200 | [diff] [blame] | 21 | static char *get_pathname(void) |
| 22 | { |
| 23 | static char pathname_array[4][PATH_MAX]; |
Ingo Molnar | 83a0944 | 2009-08-15 12:26:57 +0200 | [diff] [blame] | 24 | static int idx; |
| 25 | |
| 26 | return pathname_array[3 & ++idx]; |
Ingo Molnar | 0780060 | 2009-04-20 15:00:56 +0200 | [diff] [blame] | 27 | } |
| 28 | |
| 29 | static char *cleanup_path(char *path) |
| 30 | { |
| 31 | /* Clean it up */ |
| 32 | if (!memcmp(path, "./", 2)) { |
| 33 | path += 2; |
| 34 | while (*path == '/') |
| 35 | path++; |
| 36 | } |
| 37 | return path; |
| 38 | } |
| 39 | |
Ingo Molnar | 0780060 | 2009-04-20 15:00:56 +0200 | [diff] [blame] | 40 | char *mkpath(const char *fmt, ...) |
| 41 | { |
| 42 | va_list args; |
| 43 | unsigned len; |
| 44 | char *pathname = get_pathname(); |
| 45 | |
| 46 | va_start(args, fmt); |
| 47 | len = vsnprintf(pathname, PATH_MAX, fmt, args); |
| 48 | va_end(args); |
| 49 | if (len >= PATH_MAX) |
| 50 | return bad_path; |
| 51 | return cleanup_path(pathname); |
| 52 | } |