summaryrefslogtreecommitdiff
path: root/reference/C/EXAMPLES/strncpy.c
blob: c6c00544bb059a8ea5a06d8f7061e77633cbefd4 (plain)
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

/****************************************************************
 * 
 * Purpose: Program to demonstrate the 'strncpy' function.
 * Author:  M J Leslie
 * Date:    03-Feb-96
 * 
 ****************************************************************/

#include <string.h>	/* strcpy */

void SafeCopy(char *Dest, int DestSize, char *Source);

main()
{
    char Text1[20]="Tracy Sorrell";		/* string buffer	*/
    char Text2[10]="Martin";       		/* string buffer	*/

    printf (" Original string contents are: %s\n", Text2);

    SafeCopy(Text2, sizeof(Text2), Text1);
  
    printf (" New string contents are: %s\n", Text2);

    strcpy(Text2, "Alex");
  
    printf (" Final string contents are: %s\n", Text2);

}

/****************************************************************/

void SafeCopy(
    char     *Dest,                   /* Destination buffer. */
    int       DestSize,
    char     *Source)                 /* Source data. */
{
  
    /* ...	Copy 'Source' into 'Dest'.
     * ...        'Dest' is padded with NULLs if 'Source' is smaller.. */
  
    strncpy(Dest, Source, DestSize);
  
    /* ...	Safety net! Add the NULL just in case 'Source' is larger
     * ...	than 'Dest'.  */
  
    Dest[DestSize-1] = '\0';
}