Back to index

glibc  2.9
stpncpy.c
Go to the documentation of this file.
00001 /* Copyright (C) 1993, 1995, 1996, 1997, 2002 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003 
00004    The GNU C Library is free software; you can redistribute it and/or
00005    modify it under the terms of the GNU Lesser General Public
00006    License as published by the Free Software Foundation; either
00007    version 2.1 of the License, or (at your option) any later version.
00008 
00009    The GNU C Library is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY; without even the implied warranty of
00011    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012    Lesser General Public License for more details.
00013 
00014    You should have received a copy of the GNU Lesser General Public
00015    License along with the GNU C Library; if not, write to the Free
00016    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00017    02111-1307 USA.  */
00018 
00019 /* This is almost copied from strncpy.c, written by Torbjorn Granlund.  */
00020 
00021 #ifdef HAVE_CONFIG_H
00022 # include <config.h>
00023 #endif
00024 
00025 #ifdef _LIBC
00026 # include <string.h>
00027 #else
00028 # include <sys/types.h>
00029 #endif
00030 
00031 #ifndef weak_alias
00032 # define __stpncpy stpncpy
00033 #endif
00034 
00035 /* Copy no more than N characters of SRC to DEST, returning the address of
00036    the terminating '\0' in DEST, if any, or else DEST + N.  */
00037 char *
00038 __stpncpy (dest, src, n)
00039      char *dest;
00040      const char *src;
00041      size_t n;
00042 {
00043   char c;
00044   char *s = dest;
00045 
00046   if (n >= 4)
00047     {
00048       size_t n4 = n >> 2;
00049 
00050       for (;;)
00051        {
00052          c = *src++;
00053          *dest++ = c;
00054          if (c == '\0')
00055            break;
00056          c = *src++;
00057          *dest++ = c;
00058          if (c == '\0')
00059            break;
00060          c = *src++;
00061          *dest++ = c;
00062          if (c == '\0')
00063            break;
00064          c = *src++;
00065          *dest++ = c;
00066          if (c == '\0')
00067            break;
00068          if (--n4 == 0)
00069            goto last_chars;
00070        }
00071       n -= dest - s;
00072       goto zero_fill;
00073     }
00074 
00075  last_chars:
00076   n &= 3;
00077   if (n == 0)
00078     return dest;
00079 
00080   for (;;)
00081     {
00082       c = *src++;
00083       --n;
00084       *dest++ = c;
00085       if (c == '\0')
00086        break;
00087       if (n == 0)
00088        return dest;
00089     }
00090 
00091  zero_fill:
00092   while (n-- > 0)
00093     dest[n] = '\0';
00094 
00095   return dest - 1;
00096 }
00097 #ifdef weak_alias
00098 libc_hidden_def (__stpncpy)
00099 weak_alias (__stpncpy, stpncpy)
00100 #endif