|
|
coherent
strncpy() String Function strncpy()
Copy one string into another
#include <string.h>
cchhaarr *ssttrrnnccppyy(_s_t_r_i_n_g_1, _s_t_r_i_n_g_2, _n)
cchhaarr *_s_t_r_i_n_g_1, *_s_t_r_i_n_g_2; uunnssiiggnneedd _n;
strncpy copies up to n bytes of string2 into string1, and returns
string1. Copying ends when n bytes have been copied or a null
character has been encountered, whichever comes first. If
string2 is less than n characters in length, string2 is padded to
length n with one or more null bytes.
***** Example *****
This example, called sswwaapp.cc, 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 ssttrrnnccppyy, ssttrrnnccaatt, ssttrrnnccmmpp, and iinnddeexx.
#include <stdio.h>
#define NNAMES 512
#define MAXLEN 60
char *array[NNAMES];
char gname[MAXLEN], lname[MAXLEN];
extern int strncmp(), strcomp();
extern char *strcpy(), *strncpy(), *strncat(), *index();
main(argc, argv)
int argc; char *argv[];
{
FILE *fp;
register int count, num;
register char *name, string[60], *cptr, *eptr;
unsigned glength, length;
COHERENT Lexicon Page 1
strncpy() String Function strncpy()
if (--argc != 1) {
fprintf (stderr, "Usage: swap filename\n");
exit(1);
}
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(0);
}
***** See Also *****
strcpy(), string functions, string.h
COHERENT Lexicon Page 2
strncpy() String Function strncpy()
***** Notes *****
string1 must point to enough space to n bytes; otherwise, a por-
tion of the program or operating system may be overwritten.
COHERENT Lexicon Page 3
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.