strncat函数

来源:互联网 发布:linux 指定jdk执行jar 编辑:程序博客网 时间:2024/05/16 04:08
/*原型:extern char *strncat(char *dest,char *src,int n);用法:#include <string.h>功能:把src所指字符串的前n个字符添加到dest结尾处(覆盖dest结尾处的'\0')并添加'\0'。说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。返回指向dest的指针。*/#include <stdio.h>#include <string.h>char *strncat(char *dst, const char *src, size_t n){  if (n != 0)  {    //保存两个操作字符串的首地址    char *d = dst;    const char *s = src;    //将指向dst的指针d移到字符串末尾,指向'\0'    while (*d != 0)      d++;     //复制过程    do {      //如果到达了src字符串的末尾,则复制终止      if ((*d = *s++) == 0)        break;      //移向下一个元素      d++;    } while (--n != 0); //复制后剩余要复制的元素个数    *d = 0; //复制完毕后,将最后一个元素置为'\0'  }  return dst; }int main() {    char str[50] = "Hello ";    char str2[50] = "World!";    strcat(str, str2);    strncat(str, " Goodbye World!", 3);    puts(str);}


 

 

//linux源码

#ifndef __HAVE_ARCH_STRNCAT   /**  * strncat - Append a length-limited, %NUL-terminated string to another  * @dest: The string to be appended to  * @src: The string to append to it  * @count: The maximum numbers of bytes to copy  *  * Note that in contrast to strncpy(), strncat() ensures the result is  * terminated.  */  char *strncat(char *dest, const char *src, size_t count)  {      char *tmp = dest;        if (count) {          while (*dest)              dest++;          while ((*dest++ = *src++) != 0) {              if (--count == 0) {                  *dest = '\0';                  break;              }          }      }      return tmp;  }  EXPORT_SYMBOL(strncat);  #endif   


 

 

//标准C源码

/****strncat.c - append n chars of string to new string**       Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.**Purpose:*       defines strncat() - appends n characters of string onto*       end of other string********************************************************************************/#include <cruntime.h>#include <string.h>/****char *strncat(front, back, count) - append count chars of back onto front**Purpose:*       Appends at most count characters of the string back onto the*       end of front, and ALWAYS terminates with a null character.*       If count is greater than the length of back, the length of back*       is used instead.  (Unlike strncpy, this routine does not pad out*       to count characters).**Entry:*       char *front - string to append onto*       char *back - string to append*       unsigned count - count of max characters to append**Exit:*       returns a pointer to string appended onto (front).**Uses:**Exceptions:********************************************************************************/char * __cdecl strncat (        char * front,        const char * back,        size_t count        ){        char *start = front;        while (*front++)                ;        front--;        while (count--)                if (!(*front++ = *back++))                        return(start);        *front = '\0';        return(start);}


 

原创粉丝点击