This documentation is copyright © 1998-2001 Sandro Sigala <sandro@sigala.it>.
All rights reserved.

Released under the GNU General Public License.

Return to index Return to header Previous symbol Next symbol

strncpy

Prototype

#include <string.h>

char *strncpy(char *dest, const char *src, size_t n);

Description

Copies the first n characters of the specified string src in the buffer dest overwriting the previous existing data. If there is no terminating null character among the first n characters of the string src, the dest string will not be null-terminated. If the length of the src string is less than n, the remaining characters of dest will be padded with null characters. The dest buffer should be large enough to contain the new string. The two strings should not overlap. Returns the dest parameter.
For example, in the following code the n parameter is less than the size of the src string:
char buf[12];
strncpy(buf, "a string", 5);
this is the state of the buf array before and after the call of strncpy (? means any character):


In this second example the n parameter is greaten than the size of the src string:

char buf[12];
strncpy(buf, "a string", 11);
this is the state of the buf array before and after the call of strncpy:

Implementation

View source
#include <string.h>

char *strncpy(char *dest, const char *src, size_t n)
{
    char *dp = dest;

    while (n-- > 0 && (*dp++ = *src++) != '\0')
	;
    while (n-- > 0)
	*dp++ = '\0';

    return dest;
}

Example

View source
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char buf[10];

    strcpy(buf, "abcdefghi");	 /* buf = "abcdefghi\0" */
    strncpy(buf, "-+-+-", 5);	 /* buf = "-+-+-fghi\0" */
    printf("%s\n", buf);	 /* Prints "-+-+-fghi". */
    printf("%d\n", strlen(buf)); /* Prints "9". */

    strcpy(buf, "abcdefghi");	 /* buf = "abcdefghi\0" */
    strncpy(buf, "-+-+-", 6);	 /* buf = "-+-+-\0ghi\0" */
    printf("%s\n", buf);	 /* Prints "-+-+-". */
    printf("%d\n", strlen(buf)); /* Prints "5". */

    return EXIT_SUCCESS;
}

References

ISO C 9899:1990 7.11.2.4