path.c 967 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. static char bad_path[] = "/bad-path/";
  15. /*
  16. * One hack:
  17. */
  18. static char *get_pathname(void)
  19. {
  20. static char pathname_array[4][PATH_MAX];
  21. static int idx;
  22. return pathname_array[3 & ++idx];
  23. }
  24. static char *cleanup_path(char *path)
  25. {
  26. /* Clean it up */
  27. if (!memcmp(path, "./", 2)) {
  28. path += 2;
  29. while (*path == '/')
  30. path++;
  31. }
  32. return path;
  33. }
  34. char *mkpath(const char *fmt, ...)
  35. {
  36. va_list args;
  37. unsigned len;
  38. char *pathname = get_pathname();
  39. va_start(args, fmt);
  40. len = vsnprintf(pathname, PATH_MAX, fmt, args);
  41. va_end(args);
  42. if (len >= PATH_MAX)
  43. return bad_path;
  44. return cleanup_path(pathname);
  45. }