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" |
| 14 | |
| 15 | static char bad_path[] = "/bad-path/"; |
| 16 | /* |
Arnaldo Carvalho de Melo | 814b3f5 | 2016-06-16 17:10:46 -0300 | [diff] [blame^] | 17 | * One hack: |
Ingo Molnar | 0780060 | 2009-04-20 15:00:56 +0200 | [diff] [blame] | 18 | */ |
Ingo Molnar | 0780060 | 2009-04-20 15:00:56 +0200 | [diff] [blame] | 19 | static char *get_pathname(void) |
| 20 | { |
| 21 | static char pathname_array[4][PATH_MAX]; |
Ingo Molnar | 83a0944 | 2009-08-15 12:26:57 +0200 | [diff] [blame] | 22 | static int idx; |
| 23 | |
| 24 | return pathname_array[3 & ++idx]; |
Ingo Molnar | 0780060 | 2009-04-20 15:00:56 +0200 | [diff] [blame] | 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 | |
Ingo Molnar | 0780060 | 2009-04-20 15:00:56 +0200 | [diff] [blame] | 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 | } |