请问strncpy如何实现?

hu1hao2 2006-03-30 04:27:08
char *strnpy( char *str1, const char *str2, size_t count);

函数strncpy()把str2中的count个字符拷贝到串str1中

...全文
1121 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
iamcaicainiao 2006-03-30
  • 打赏
  • 举报
回复
搜索一下老贴。
firetoucher 2006-03-30
  • 打赏
  • 举报
回复
GNU C Lib Function, FYI:


char *
strncpy (s1, s2, n)
char *s1;
const char *s2;
size_t n;
{
reg_char c;
char *s = s1;

--s1;

if (n >= 4)
{
size_t n4 = n >> 2;

for (;;)
{
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
if (--n4 == 0)
goto last_chars;
}
n = n - (s1 - s) - 1;
if (n == 0)
return s;
goto zero_fill;
}

last_chars:
n &= 3;
if (n == 0)
return s;

do
{
c = *s2++;
*++s1 = c;
if (--n == 0)
return s;
}
while (c != '\0');

zero_fill:
do
*++s1 = '\0';
while (--n > 0);

return s;
}

FT
--
Anything one man can imagine, other men can make real.
jinjiajie 2006-03-30
  • 打赏
  • 举报
回复
没日经贴哪来得分,嘿嘿
Michael_555 2006-03-30
  • 打赏
  • 举报
回复
char *GSMstrncpy( char *Dst, const char *Src, int MaxLen )
{
char *D = Dst;

while ( MaxLen )
{
/* Decrement inside the loop so it only happens when a char is copied */
MaxLen--;

if ( ( *D++ = *Src++ ) == 0 )
break;
}

/* Pad the rest of the specified length with zeros */
while ( MaxLen-- )
*D++ = '\0';

return Dst;
}
yinqing_yx 2006-03-30
  • 打赏
  • 举报
回复
论坛上有strcpy实现的很多帖子 判断加个范围限制就行了~
jixingzhong 2006-03-30
  • 打赏
  • 举报
回复
就是全部拷贝的 N 版 ...
strcpy 增加一个拷贝字符数目的检测就是了 。
qybao 2006-03-30
  • 打赏
  • 举报
回复
for example
char *strnpy( char *str1, const char *str2, size_t count) {
if (str1==MULL or str2==NULL) return str1;
int i = 0;
while (*(str2+i)!='\0' && i<count) {
*(str1+i) = *(str2+i);
i++;
}
*(str1+i) = '\0';

return str1;
}
duduhaha 2006-03-30
  • 打赏
  • 举报
回复
unix v7源代码
/*
* Copy s2 to s1, truncating or null-padding to always copy n bytes
* return s1
*/

char *
strncpy(s1, s2, n)
register char *s1, *s2;
{
register i;
register char *os1;

os1 = s1;
for (i = 0; i < n; i++)
if ((*s1++ = *s2++) == '\0') {
while (++i < n)
*s1++ = '\0';
return(os1);
}
return(os1);
}
ykzhujiang 2006-03-30
  • 打赏
  • 举报
回复
这个快成日经了
实现不难,注意考虑各种边界情况就可以了,发扬一下diy精神

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧