From 954b7eb9d84576a5e4c02e7958201da728d5e092 Mon Sep 17 00:00:00 2001 From: hugogogo Date: Sat, 2 May 2026 11:58:09 +0200 Subject: [PATCH] adding ft_strjoin_static --- Makefile | 1 + includes/libft.h | 1 + srcs/ft_strjoin_static.c | 42 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 srcs/ft_strjoin_static.c diff --git a/Makefile b/Makefile index 219982e..43403a4 100644 --- a/Makefile +++ b/Makefile @@ -54,6 +54,7 @@ SRCS = ft_memset.c \ ft_strncpy.c \ ft_strstr.c \ ft_strjoinfree.c \ + ft_strjoin_static.c \ ft_strclr.c \ ft_strdel.c \ ft_strequ.c \ diff --git a/includes/libft.h b/includes/libft.h index 585e735..b7f35a6 100644 --- a/includes/libft.h +++ b/includes/libft.h @@ -49,6 +49,7 @@ char *ft_strdup(const char *s1); char *ft_substr(char const *s, unsigned int start, size_t len); char *ft_strjoin(char const *s1, char const *s2); +size_t ft_strjoin_static(char *dst, size_t dst_size, const char **srcs, size_t n); char *ft_strtrim(char const *s1, char const *set); char **ft_split(char const *s, char c); char *ft_itoa(long int n); diff --git a/srcs/ft_strjoin_static.c b/srcs/ft_strjoin_static.c new file mode 100644 index 0000000..d8c71dd --- /dev/null +++ b/srcs/ft_strjoin_static.c @@ -0,0 +1,42 @@ +#include "libft.h" + +/** + * Concatenates an array of strings into a pre-allocated destination buffer. + * + * @param dst Destination buffer. + * @param dst_size Size of the destination buffer (including space for null terminator). + * @param srcs Array of source strings to concatenate. + * @param n Number of strings in `srcs`. + * @return The total length of the concatenated string (excluding null terminator), + * or 0 if the buffer is too small. + * @note The caller must ensure `dst_size > 0`. If the buffer is too small, + * the function returns 0 and `dst` is set to an empty string. + */ + +size_t ft_strjoin_static(char *dst, size_t dst_size, const char **srcs, size_t n) +{ + // Calculate total length needed + size_t total_len = 0; + for (size_t i = 0; i < n; i++) + { + total_len += ft_strlen(srcs[i]); + } + + // Check if buffer is large enough (include space for '\0') + if (total_len + 1 > dst_size) + { + dst[0] = '\0'; + return 0; + } + + // Copy strings + char *ptr = dst; + for (size_t i = 0; i < n; i++) + { + size_t len = ft_strlen(srcs[i]); + ft_memcpy(ptr, srcs[i], len); + ptr += len; + } + *ptr = '\0'; + return total_len; +} \ No newline at end of file