Line data Source code
1 : #include "precizer.h"
2 :
3 : /**
4 : * @brief Constructs an absolute path from a base directory and a relative path.
5 : *
6 : * This function dynamically allocates memory for the absolute path and combines
7 : * the given base directory (config->running_dir) with the relative path.
8 : *
9 : * @param absolute_path Pointer to store the dynamically allocated absolute path.
10 : * @param path Relative path to append.
11 : * @param path_size Size of the relative path string.
12 : */
13 9569 : Return path_absolute_from_relative(
14 : char **absolute_path,
15 : const char *path,
16 : const size_t path_size)
17 : {
18 : /// The status that will be passed to return() before exiting.
19 : /// By default, the function worked without errors.
20 9569 : Return status = SUCCESS;
21 :
22 9569 : size_t len = 0;
23 :
24 9569 : if(!absolute_path || !path)
25 : {
26 0 : provide(FAILURE);
27 : }
28 :
29 : // Allocate memory for the absolute path (base dir + '/' + relative path + null terminator)
30 9569 : if(path_size > 0 && path[0] == '/')
31 : {
32 : // The provided path is actually absolute!
33 2 : len = path_size + 1;
34 2 : *absolute_path = (char *)malloc(len);
35 :
36 2 : if(*absolute_path == NULL)
37 : {
38 0 : report("Memory allocation failed, requested size: %zu bytes",len);
39 0 : status = FAILURE;
40 0 : provide(status);
41 : }
42 :
43 2 : snprintf(*absolute_path,len,"%s",path);
44 :
45 : } else {
46 : // The provided path is indeed relative!
47 : // running_dir_size already counts the trailing '\0'; +1 adds space for '/' and the new terminator.
48 9567 : len = (size_t)config->running_dir_size + path_size + 1;
49 9567 : *absolute_path = (char *)malloc(len);
50 :
51 9567 : if(*absolute_path == NULL)
52 : {
53 0 : report("Memory allocation failed, requested size: %zu bytes",len);
54 0 : status = FAILURE;
55 0 : provide(status);
56 : }
57 :
58 9567 : snprintf(*absolute_path,len,"%s/%s",config->running_dir,path);
59 : }
60 :
61 9569 : provide(status);
62 : }
|