Line data Source code
1 : #include "testitall.h"
2 : #include <limits.h>
3 : #include <string.h>
4 :
5 : // Local helper to strip trailing slashes, keeping "/" intact.
6 1 : static void remove_trailing_slash_local(char *path)
7 : {
8 1 : if(path == NULL || *path == '\0')
9 : {
10 0 : return;
11 : }
12 :
13 1 : size_t len = strlen(path);
14 :
15 1 : while(len > 1U && path[len - 1U] == '/')
16 : {
17 0 : path[--len] = '\0';
18 : }
19 : }
20 :
21 : /**
22 : * @brief Write the parent directory of the current working directory into the buffer.
23 : *
24 : * Example: if CWD is "/tmp/precizer/run", the function writes "/tmp/precizer".
25 : *
26 : * @param path Destination buffer (e.g., char path[PATH_MAX] = {0};).
27 : * @param path_size Size of the destination buffer in bytes (e.g., sizeof(path)).
28 : * @return SUCCESS on success, FAILURE on error or insufficient space.
29 : */
30 1 : Return get_origin_dir(
31 : char *path,
32 : size_t path_size)
33 : {
34 1 : if(NULL == path || 0U == path_size)
35 : {
36 0 : return(FAILURE);
37 : }
38 :
39 1 : char *cwd = NULL;
40 :
41 : #if defined(__GLIBC__)
42 1 : cwd = get_current_dir_name();
43 : #else
44 : // Portable fallback for macOS/BSD.
45 : cwd = getcwd(NULL,0);
46 : #endif
47 :
48 1 : if(NULL == cwd)
49 : {
50 0 : path[0] = '\0';
51 0 : return(FAILURE);
52 : }
53 :
54 1 : remove_trailing_slash_local(cwd);
55 :
56 1 : const char *last_slash = strrchr(cwd,'/');
57 :
58 1 : if(NULL == last_slash)
59 : {
60 0 : path[0] = '\0';
61 0 : free(cwd);
62 0 : return(FAILURE);
63 : }
64 :
65 1 : size_t parent_len = 0U;
66 :
67 1 : if(last_slash == cwd)
68 : {
69 : /* CWD is "/" or similar; parent is "/" */
70 0 : parent_len = 1U;
71 : } else {
72 1 : parent_len = (size_t)(last_slash - cwd);
73 : }
74 :
75 1 : const size_t needed = parent_len + 1U;
76 :
77 1 : if(needed > path_size)
78 : {
79 0 : path[0] = '\0';
80 0 : free(cwd);
81 0 : return(FAILURE);
82 : }
83 :
84 1 : if(parent_len == 1U)
85 : {
86 0 : path[0] = '/';
87 0 : path[1] = '\0';
88 : } else {
89 1 : memcpy(path,cwd,parent_len);
90 1 : path[parent_len] = '\0';
91 : }
92 :
93 1 : free(cwd);
94 :
95 1 : return(SUCCESS);
96 : }
|