blob: 7c7630be5a897d651bbda7eaf2e0c4addcf95a03 [file] [log] [blame]
Ingo Molnar07800602009-04-20 15:00:56 +02001/*
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 Melo175729f2016-07-07 11:38:09 -030014#include "util.h"
15#include <limits.h>
Ingo Molnar07800602009-04-20 15:00:56 +020016
17static char bad_path[] = "/bad-path/";
18/*
Arnaldo Carvalho de Melo814b3f52016-06-16 17:10:46 -030019 * One hack:
Ingo Molnar07800602009-04-20 15:00:56 +020020 */
Ingo Molnar07800602009-04-20 15:00:56 +020021static char *get_pathname(void)
22{
23 static char pathname_array[4][PATH_MAX];
Ingo Molnar83a09442009-08-15 12:26:57 +020024 static int idx;
25
26 return pathname_array[3 & ++idx];
Ingo Molnar07800602009-04-20 15:00:56 +020027}
28
29static 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 Molnar07800602009-04-20 15:00:56 +020040char *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}