COHERENT manpages
This page displays the COHERENT manpage for strncpy() [Copy one string into another].
List of available manpages
Index
strncpy() -- String Function (libc)
Copy one string into another
#include <string.h>
char *strncpy(string1, string2, n)
char *string1, *string2; unsigned n;
strncpy() copies up to n bytes of string2 into string1, and returns
string1. Copying ends when strncpy() has copied n bytes or has encountered
a null character, whichever comes first. If string2 is less than n
characters in length, strncpy() pads string1 to length n with one or more
null bytes.
Example
This example, called swap.c, reads a file of names, and changes them from
the format
first_name [middle_initial] last_name
to the format
last_name, first_name [middle_initial]
It demonstrates strncpy(), strncat(), strncmp(), and index().
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NNAMES 512
#define MAXLEN 60
char *array[NNAMES];
char gname[MAXLEN], lname[MAXLEN];
main(argc, argv)
int argc; char *argv[];
{
FILE *fp;
register int count, num;
register char *name, string[60], *cptr, *eptr;
unsigned glength, length;
if (--argc != 1) {
fprintf (stderr, "Usage: swap filename\n");
exit(EXIT_FAILURE);
}
if ((fp = fopen(argv[1], "r")) == NULL)
printf("Cannot open %s\n", argv[1]);
count = 0;
while (fgets(string, 60, fp) != NULL) {
if ((cptr = index(string, '.')) != NULL) {
cptr++;
cptr++;
} else if ((cptr = index(string,' ')) != NULL)
cptr++;
strcpy(lname, cptr);
eptr = index(lname, '\n');
*eptr = ',';
strcat(lname," ");
glength = (unsigned)(strlen(string) - strlen(cptr));
strncpy(gname, string, glength);
name = strncat(lname, gname, glength);
length = (unsigned)strlen(name);
array[count] = malloc(length + 1);
strcpy(array[count],name);
count++;
}
for (num = 0; num < count; num++)
printf("%s\n", array[num]);
exit(EXIT_SUCCESS);
}
See Also
libc,
strcpy(),
string.h
ANSI Standard, §7.11.2.4
POSIX Standard, §8.1
Notes
string1 must point to enough space to n bytes; otherwise, a portion of the
program or operating system may be overwritten.











