ssttrrnnccppyy() -- String Function (libc)

Copy one string into another
#iinncclluuddee <ssttrriinngg.hh>
cchhaarr *ssttrrnnccppyy(_s_t_r_i_n_g_1, _s_t_r_i_n_g_2, _n)
cchhaarr *_s_t_r_i_n_g_1, *_s_t_r_i_n_g_2; uunnssiiggnneedd _n;

ssttrrnnccppyy()  copies  up to  _n  bytes  of _s_t_r_i_n_g_2  into  _s_t_r_i_n_g_1, and  returns
_s_t_r_i_n_g_1. Copying ends when ssttrrnnccppyy()  has copied _n bytes or has encountered
a  null  character, whichever  comes  first.   If _s_t_r_i_n_g_2  is  less than  _n
characters in length,  ssttrrnnccppyy() pads _s_t_r_i_n_g_1 to length _n  with one or more
null bytes.

_E_x_a_m_p_l_e
This example, called  sswwaapp.c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 ssttrrnnccppyy(), ssttrrnnccaatt(), ssttrrnnccmmpp(), and iinnddeexx().

#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);
}

_S_e_e _A_l_s_o
lliibbcc, ssttrrccppyy(), ssttrriinngg.hh
ANSI Standard, section 7.11.2.4
POSIX Standard, section 8.1

_N_o_t_e_s
_s_t_r_i_n_g_1 must point to enough space  to _n bytes; otherwise, a portion of the
program or operating system may be overwritten.
