]> pd.if.org Git - pdclib/blob - functions/string/strncpy.c
Failed to terminate correctly at n < strlen(s2). Fixed. Thanks to the bug reporter.
[pdclib] / functions / string / strncpy.c
1 /* $Id$ */
2
3 /* strncpy( char *, const char *, size_t )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 #include <string.h>
10
11 /* TODO: Debuggung only */
12 #include <stdio.h>
13
14 #ifndef REGTEST
15
16 char * strncpy( char * _PDCLIB_restrict s1, const char * _PDCLIB_restrict s2, size_t n )
17 {
18     char * rc = s1;
19     while ( ( n > 0 ) && ( *s1++ = *s2++ ) )
20     {
21         /* Cannot do "n--" in the conditional as size_t is unsigned and we have
22            to check it again for >0 in the next loop.
23         */
24         --n;
25     }
26     /* TODO: This works correctly, but somehow the handling of n is ugly as
27        hell.
28     */
29     if ( n > 0 )
30     {
31         while ( --n )
32         {
33             *s1++ = '\0';
34         }
35     }
36     return rc;
37 }
38
39 #endif
40
41 #ifdef TEST
42 #include <_PDCLIB_test.h>
43
44 int main( void )
45 {
46     char s[] = "xxxxxxx";
47     TESTCASE( strncpy( s, "", 1 ) == s );
48     TESTCASE( s[0] == '\0' );
49     TESTCASE( s[1] == 'x' );
50     TESTCASE( strncpy( s, abcde, 6 ) == s );
51     TESTCASE( s[0] == 'a' );
52     TESTCASE( s[4] == 'e' );
53     TESTCASE( s[5] == '\0' );
54     TESTCASE( s[6] == 'x' );
55     TESTCASE( strncpy( s, abcde, 7 ) == s );
56     TESTCASE( s[6] == '\0' );
57     TESTCASE( strncpy( s, "xxxx", 3 ) == s );
58     TESTCASE( s[0] == 'x' );
59     TESTCASE( s[2] == 'x' );
60     TESTCASE( s[3] == 'd' );
61     return TEST_RESULTS;
62 }
63 #endif