42 lines
1.2 KiB
C
42 lines
1.2 KiB
C
#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;
|
|
} |