Skip to content

strlcat

Marcos edited this page Oct 2, 2024 · 2 revisions

Función ft_strlcat

La función ft_strlcat concatena la cadena src al final de la cadena dst, asegurando que el resultado esté siempre terminado en nulo ('\0'), y que no se escriban más de dstsize - 1 caracteres en dst.

Explicación del comando man

STRLCAT(3) (simplified)

NAME
    strlcat -- size-bounded string concatenation
SYNOPSIS
    size_t strlcat(char *dst, const char *src, size_t dstsize);
DESCRIPTION
    The strlcat() function concatenate strings with the same input parameters and outuput result as snprintf(3). It is designed to be safer, more consistent, and less error prone replacements for the easily misused function strncat(3).
    strlcat() take the full size of the destination buffer and guarantee NUL-termination if there is room. Note that room for the NUL should be included in dstsize. Also note that strlcat() only operate on true ''C'' strings. This means that both src and dst must be NUL-terminated.
    strlcat() appends string src to the end of dst. It will append at most dstsize - strlen(dst) - 1 characters. It will then NUL-terminate, unless dstsize is 0 or the original dst string was longer than dstsize (in practice this should not happen as it means that either dstsize is incorrect or that dst is not a proper string).
    If the src and dst strings overlap, the behavior is undefinded.
RETURN VALUES
    Like snprintf(3), strlcat() function return the total length of the string it tried to create. That means the initial length of dst plus the length of src.
    If the return value is >= dstsize, the output string has been truncated.
    It is the caller's responsibility to handle this.

Explicación con mis palabras

La función strlcat() concatena la cadena src al final de la cadena dst, asegurándose de no escribir más de dstsize - 1 caracteres, y de que la cadena dst esté terminada en nulo ('\0'). El valor retornado es la longitud total de la cadena que se intentó crear, es decir, la longitud inicial de dst más la longitud de src.

Implementación en C

Aquí te muestro mi implementación de la función ft_strlcat en mi proyecto de Libft.

Código de ft_strlcat

#include "libft.h"

size_t	ft_strlcat(char *dst, const char *src, size_t dstsize)
{
	size_t	dest_len;
	size_t	src_len;
	size_t	i;
	size_t	total_len;

	// Calculamos la longitud de la cadena destino
	dest_len = 0;
	while (dst[dest_len])
		dest_len++;

	// Calculamos la longitud de la cadena fuente
	src_len = 0;
	while (src[src_len])
		src_len++;

	// Si el tamaño del destino es menor o igual a dest_len, retornamos el tamaño total esperado
	if (dstsize <= dest_len)
		return (dstsize + src_len);

	// Concatenamos src a dst, respetando el límite de dstsize
	i = 0;
	while (src[i] != '\0' && dest_len + i < dstsize - 1)
	{
		dst[dest_len + i] = src[i];
		i++;
	}

	// Aseguramos la terminación en '\0'
	dst[dest_len + i] = '\0';

	// Calculamos y retornamos la longitud total de la cadena resultante
	total_len = dest_len + src_len;
	return (total_len);
}

Main para probar ft_strlcat

El siguiente código es un ejemplo de cómo puedes probar la función ft_strlcat():

#include <stdio.h>

size_t	ft_strlcat(char *dst, const char *src, size_t dstsize);

int main(void)
{
	char dst[20] = "Hello";
	char src[] = " World";
	size_t length;

	length = ft_strlcat(dst, src, sizeof(dst));
	printf("Cadena concatenada: %s\n", dst);
	printf("Longitud total: %zu\n", length); // Debe devolver 11 (longitud de "Hello World")

	return 0;
}

Recomendaciones o ejemplos de uso

  • ¿Por qué usar strlcat?
    strlcat es útil cuando necesitas concatenar cadenas de manera segura, evitando desbordamientos de buffer al respetar el tamaño máximo del buffer de destino y garantizando que la cadena resultante siempre esté terminada en nulo ('\0').

  • ¿Cuándo usar strlcat?
    Usa strlcat cuando necesites combinar dos cadenas en un buffer cuyo tamaño es limitado, y no quieres arriesgarte a que se produzca un desbordamiento de buffer. Es ideal para aplicaciones que manejan entradas de usuario o concatenación de cadenas en redes o archivos.

Clone this wiki locally