strncat() And strncpy()

strncat

Name

strcat, strncat - concatenate two strings

Synopsis

#include <string.h>

char *strcat(char *dest, const char *src);
 
char *strncat(char *dest, const char *src, size_t n);

Description

The strcat() function appends the src string to the dest string, overwriting the terminating null byte('\0') at the end of dest, and then adds a terminating null byte.The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough,program behavior is unpredictable; buffer overruns are a favorite avenue for attacking secure programs.

The strncat() function is similar, exceptthat

*

it will use at most n bytes from src;and

*

src does not need to be null-terminated if it contains n or more bytes.

As with strcat(), the resulting string in dest is always null-terminated.

If src contains n or more bytes, strncat() writes n+1 bytes to dest (n from src plus the terminating null byte). Therefore, the size of dest must be at least strlen(dest)+n+1.

A simple implementation of strncat() might be:

char*
strncat(char *dest, const char *src, size_tn)
{
   size_t dest_len = strlen(dest);
   size_t i;
 
   for(i = 0 ; i < n && src[i] != '\0' ; i++)
       dest[dest_len + i] = src[i];
   dest[dest_len + i] = '\0';
 
  return dest;
}

Return Value

The strcat() and strncat() functions return a pointer to the resulting string dest.

 

strncpy

Name

strcpy, strncpy - copy a string

Synopsis


#include <string.h>

char *strcpy(char *dest, const char *src);
 
char *strncpy(char *dest, const char *src, size_t n);


Description

The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns! (See BUGS.)

The strncpy() function is similar, except that at most n bytes of src are copied. Warning:If there is no null byte among the first n bytes of src,the string placed in dest will not be null-terminated.

If the length of src is less than nstrncpy() writes additional null bytes to dest to ensure that a total of n bytes are written.

A simple implementation of strncpy() might be:

char *
strncpy(char *dest, const char *src, size_tn)
{
   size_t i;
 
   for(i = 0; i < n && src[i] != '\0'; i++)
       dest[i] = src[i];
    for( ; i < n; i++)
       dest[i] = '\0';
 
  return dest;
}

Return Value

The strcpy() and strncpy() functions return a pointer to the destination string dest.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值