Sams Teach Yourself C in 21 Days

(singke) #1
Manipulating Strings 485

17


Thestrncpy()Function ................................................................................

Thestrncpy()function is similar to strcpy(), except that strncpy()lets you specify
how many characters to copy. Its prototype is
char *strncpy(char *destination, const char *source, size_t n);
The arguments destinationandsourceare pointers to the destination and source
strings. The function copies, at most, the first ncharacters of sourcetodestination. If
sourceis shorter than ncharacters, enough null characters are added at the end of
sourceto make a total of ncharacters copied to destination. If sourceis longer than n
characters, no terminating \0is added to destination. The function’s return value is
destination.
Listing 17.3 demonstrates the use of strncpy().

LISTING17.3 strncpy.c. The strncpy()function
1: /* Using the strncpy() function. */
2:
3: #include <stdio.h>
4: #include <string.h>
5:
6: char dest[] = “..........................”;
7: char source[] = “abcdefghijklmnopqrstuvwxyz”;
8:
9: int main( void )
10: {
11: size_t n;
12:
13: while (1)
14: {
15: puts(“Enter the number of characters to copy (1-26)”);
16: scanf(“%d”, &n);
17:
18: if (n > 0 && n< 27)
19: break;
20: }
21:
22: printf(“\nBefore strncpy destination = %s”, dest);
23:
24: strncpy(dest, source, n);
25:
26: printf(“\nAfter strncpy destination = %s\n”, dest);
27: return 0;
28: }

28 448201x-CH17 8/13/02 11:13 AM Page 485

Free download pdf