File: Strn.c

package info (click to toggle)
ncftp 1%3A2.4.3-4
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 868 kB
  • ctags: 1,231
  • sloc: ansic: 13,766; makefile: 174; sh: 1
file content (79 lines) | stat: -rw-r--r-- 2,078 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <string.h>
#include <sys/types.h>
#include "Strn.h"

/*
 * Concatenate src on the end of dst.  The resulting string will have at most
 * n-1 characters, not counting the NUL terminator which is always appended
 * unlike strncat.  The other big difference is that strncpy uses n as the
 * max number of characters _appended_, while this routine uses n to limit
 * the overall length of dst.
 */
char *Strncat(char *dst, char *src, size_t n)
{
	register size_t i;
	register char *d, *s;

	if (n != 0 && ((i = strlen(dst)) < (n - 1))) {
		d = dst + i;
		s = src;
		/* If they specified a maximum of n characters, use n - 1 chars to
		 * hold the copy, and the last character in the array as a NUL.
		 * This is the difference between the regular strncpy routine.
		 * strncpy doesn't guarantee that your new string will have a
		 * NUL terminator, but this routine does.
		 */
		for (++i; i<n; i++) {
			if ((*d++ = *s++) == 0) {
				/* Pad with zeros. */
				for (; i<n; i++)
					*d++ = 0;
				return dst;
			}
		}
		/* If we get here, then we have a full string, with n - 1 characters,
		 * so now we NUL terminate it and go home.
		 */
		*d = 0;
	}
	return (dst);
}	/* Strncat */


/*
 * Copy src to dst, truncating or null-padding to always copy n-1 bytes.
 * Return dst.
 */
char *Strncpy(char *dst, char *src, size_t n)
{
	register char *d;
	register char *s;
	register size_t i;

	d = dst;
	*d = 0;
	if (n != 0) {
		s = src;
		/* If they specified a maximum of n characters, use n - 1 chars to
		 * hold the copy, and the last character in the array as a NUL.
		 * This is the difference between the regular strncpy routine.
		 * strncpy doesn't guarantee that your new string will have a
		 * NUL terminator, but this routine does.
		 */
		for (i=1; i<n; i++) {
			if ((*d++ = *s++) == 0) {
				/* Pad with zeros. */
				for (; i<n; i++)
					*d++ = 0;
				return dst;
			}
		}
		/* If we get here, then we have a full string, with n - 1 characters,
		 * so now we NUL terminate it and go home.
		 */
		*d = 0;
	}
	return (dst);
}	/* Strncpy */

/* eof Strn.c */