From ac84cd4d527fd4730d166ec56efc7e09cb8c93c4 Mon Sep 17 00:00:00 2001 From: Jan Schmidt Date: Sat, 27 May 2023 17:44:34 +1000 Subject: [PATCH] util/u_file: Add u_file_open_file_in_config_dir_subpath() Add a utility function for accessing files in subdirectories of the main config dir, creating the subpath as needed. --- src/xrt/auxiliary/util/u_file.c | 33 +++++++++++++++++++++++++++++++++ src/xrt/auxiliary/util/u_file.h | 3 +++ 2 files changed, 36 insertions(+) diff --git a/src/xrt/auxiliary/util/u_file.c b/src/xrt/auxiliary/util/u_file.c index 74585a25d..e892fbccc 100644 --- a/src/xrt/auxiliary/util/u_file.c +++ b/src/xrt/auxiliary/util/u_file.c @@ -119,6 +119,39 @@ u_file_open_file_in_config_dir(const char *filename, const char *mode) return fopen(file_str, mode); } +FILE * +u_file_open_file_in_config_dir_subpath(const char *subpath, const char *filename, const char *mode) +{ + char tmp[PATH_MAX]; + int i = u_file_get_config_dir(tmp, sizeof(tmp)); + if (i < 0 || i >= (int)sizeof(tmp)) { + return NULL; + } + + char fullpath[PATH_MAX]; + i = snprintf(fullpath, sizeof(fullpath), "%s/%s", tmp, subpath); + if (i < 0 || i >= (int)sizeof(fullpath)) { + return NULL; + } + + char file_str[PATH_MAX + 15]; + i = snprintf(file_str, sizeof(file_str), "%s/%s", fullpath, filename); + if (i < 0 || i >= (int)sizeof(file_str)) { + return NULL; + } + + FILE *file = fopen(file_str, mode); + if (file != NULL) { + return file; + } + + // Try creating the path. + mkpath(fullpath); + + // Do not report error. + return fopen(file_str, mode); +} + ssize_t u_file_get_hand_tracking_models_dir(char *out_path, size_t out_path_size) { diff --git a/src/xrt/auxiliary/util/u_file.h b/src/xrt/auxiliary/util/u_file.h index b2277a75c..753a334db 100644 --- a/src/xrt/auxiliary/util/u_file.h +++ b/src/xrt/auxiliary/util/u_file.h @@ -28,6 +28,9 @@ u_file_get_path_in_config_dir(const char *suffix, char *out_path, size_t out_pat FILE * u_file_open_file_in_config_dir(const char *filename, const char *mode); +FILE * +u_file_open_file_in_config_dir_subpath(const char *subpath, const char *filename, const char *mode); + ssize_t u_file_get_hand_tracking_models_dir(char *out_path, size_t out_path_size);