LoginSignup
5
3

strlcat自作

Last updated at Posted at 2022-04-17

man strlcat!!!!

SYNOPSIS
     #include <string.h>
     size_t
     strlcat(char * restrict dst, const char * restrict src, size_t dstsize);
DESCRIPTION
 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 undefined.

オーバーラップした時は未定義か。。(·ε·`)スネチャウ

検証

strlcatの挙動を見てみよう
ここでは
コピー先の文字列(1つ目の引数)ことをdest
コピー元の文字列(2つ目の引数)ことをstr
と呼びますね!

xがdest文字数以下の時
#include <stdio.h>
#include <string.h>

int main()
{
    char dest[20] = "ABCDE";
    char src[] = "1234";
    int x = 2;
   
    unsigned int result1 = strlcat(dest, src, x);
    printf("%s: %u\n", dest, result1);
    return(0);
}
結果
ABCDE: 6

xがdest文字数以下の時(x=2)
destの文字列は変わらない
返り値は6
6はx+str文字数

xが(dast文字数+str文字数)以下の時
#include <stdio.h>
#include <string.h>

int main()
{
    char dest[20] = "ABCDE";
    char src[] = "1234";
    int x = 7;
   
    unsigned int result1 = strlcat(dest, src, x);
    printf("%s: %u\n", dest, result1);
    return(0);
}
結果
ABCDE1: 9

xが(dest文字数+src文字数)以下の時
destの文字列の後ろにsrcが(x-dest文字数-1)文字ペーストされてる??
返り値は9(destの文字数+srcの文字数)ゲッ!(꒪ꇴ꒪|||)⚡

xがdestの文字数+srcの文字数より大きい時の時
#include <stdio.h>
#include <string.h>

int main()
{
    char dest[20] = "ABCDE";
    char src[] = "1234";
    int x = 13;
   
    unsigned int result1 = strlcat(dest, src, x);
    printf("%s: %u\n", dest, result1);
    return(0);
}
結果
ABCDE1234: 9

xがコピー先の文字数以上コピー先の文字数+コピー元の文字数よりおおきい時
destの文字列の後ろにsrcの文字列がペーストされてる
返り値は9(destの文字数+srcの文字数)

わかったこと

strlcatはdestとsrcを結合させる
destの後ろにsrcを最大(x-dest文字数-1)文字ペーストしてくれる
返り値は、dest文字数がx以上の時は(x+src文字数)
xよりdestの文字数が小さい時は時は(dest文字数+src文字数)
BF5F110C-62D2-4E2F-B1CB-6F224F80406D.jpg


unsigned int	len_str(char *str)
{
	unsigned int	count;

	count = 0;
	while (str[count])
		count++;
	return (count);
}//文字数数える

unsigned int	ft_strlcat(char *dest, char *src, unsigned int size)
{
	unsigned int	k;
	unsigned int	max_copy;
	unsigned int	d_nb;
	unsigned int	s_nb;

	d_nb = len_str(dest);
	s_nb = len_str(src);
	if (size <= d_nb)
		return (size + s_nb);
	max_copy = size - d_nb - 1;
	k = 0;
	while (k < max_copy)
	{
		if (src[k] == '\0')
			break ;
		dest[d_nb + k] = src[k];
		k++;
	}
	dest[k + d_nb] = '\0';
	return (s_nb + d_nb);
}

大城希乃樺ちゃん疲れたでござる

5
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3