cwk_path_get_relative.md (3030B)
1 --- 2 title: cwk_path_get_relative 3 description: Generates a relative path based on a base. 4 --- 5 6 _(since v1.0.0)_ 7 Generates a relative path based on a base. 8 9 ## Description 10 ```c 11 size_t cwk_path_get_relative(const char *base_directory, const char *path, 12 char *buffer, size_t buffer_size); 13 ``` 14 15 This function generates a relative path based on a base path and another path. It determines how to get to the submitted path, starting from the base directory. The result will be written to a buffer, which might be truncated if the buffer is not large enough to hold the full path. However, the truncated result will always be null-terminated. The returned value is the amount of characters which the resulting path would take if it was not truncated (excluding the null-terminating character). 16 17 ## Parameters 18 * **base_directory**: The base path from which the relative path will start. 19 * **path**: The target path where the relative path will point to. 20 * **buffer**: The buffer where the result will be written to. 21 * **buffer_size**: The size of the result buffer. 22 23 ## Return Value 24 Returns the total amount of characters of the full path. 25 26 ## Outcomes 27 28 | Style | Base | Path | Result | 29 |---------|--------------------------|--------------------------|-----------------| 30 | UNIX | ``/../../`` | ``/../../`` | ``.`` | 31 | UNIX | ``/path/same`` | ``/path/not_same/ho/..`` | ``../not_same`` | 32 | UNIX | ``/path/not_same/ho/..`` | ``/path/same`` | ``../same`` | 33 | UNIX | ``/path/same`` | ``/path/same/ho/..`` | ``.`` | 34 | UNIX | ``/path/same/ho/..`` | ``/path/same`` | ``.`` | 35 | UNIX | ``/path/same`` | ``/path/same`` | ``.`` | 36 | UNIX | ``/path/long/one`` | ``/path/long/one/two`` | ``two`` | 37 | UNIX | ``/path/long/one/two`` | ``/path/long/one`` | ``..`` | 38 | UNIX | ``./this/is/path_one`` | ``./this/is/path_two`` | ``../path_two`` | 39 | UNIX | ``/this/is/path_one`` | ``/this/is/path_two`` | ``../path_two`` | 40 | WINDOWS | ``C:/path/same`` | ``D:/path/same`` | `` `` | 41 42 ## Example 43 ```c 44 #include <cwalk.h> 45 #include <stdio.h> 46 #include <stddef.h> 47 #include <stdlib.h> 48 49 int main(int argc, char *argv[]) 50 { 51 char buffer[FILENAME_MAX]; 52 53 cwk_path_get_relative("/hello/there/", "/hello/world", buffer, sizeof(buffer)); 54 printf("The relative path is: %s", buffer); 55 56 return EXIT_SUCCESS; 57 } 58 ``` 59 60 Ouput: 61 ``` 62 The relative path is: ../world 63 ``` 64 65 ## Changelog 66 67 | Version | Description | 68 |------------|---------------------------------------------------| 69 | **v1.2.7** | Fixed windows paths with forward slashes in root. | 70 | **v1.2.5** | Fixed calls with path without segments. | 71 | **v1.2.5** | Fixed calls with unequal roots in paths. | 72 | **v1.0.0** | The function is introduced. |