Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

strfill - Copy part of a string

&pagelevel(4)&pagelevel

Definition

#include <string.h>

char *strfill(char *s1, const char *s2, size_t n);

strfill copies a maximum of n characters from string s2 to string s1.

The manner in which copying takes place is determined by the lengths and contents of strings s1 and s2 and the value specified for n.

  1. Regardless of the length of string s1, n characters are always copied to s1 (in all cases except case 5). In other words,

    • If s1 contains more than n characters, the characters remaining at the right in s1 are retained.

    • If s1 contains fewer than n characters, s1 is lengthened up to a length of n. In this case, s1 is not automatically terminated with a null byte (cf. notes).

  2. s2 contains fewer than n characters:

    In addition to the characters copied from s2, the number of blanks required to achieve a total of n are added.

  3. s2 contains more than n characters:

    Only the first n characters from s2 are copied.

  4. s2 is a null string:

    s1 is padded with n blanks.

  5. s2 is passed as a NULL pointer:

    (n - strlen(s1)) blanks are appended to string s1. If this subtraction yields a negative result or 0, i.e. if the number of characters in s1 is greater than or equal to n, the contents of s1 remain unchanged.

Return val.

Pointer to the result string s1.

Notes

Strings terminated with the null byte (\0) are expected as arguments.

strfill does not check whether s1 is large enough for the result and does not automatically terminate the result string with the null byte (\0)! To avoid an unpredictable result, you should explicitly terminate string s1 with the null byte after each strfill call (see the example).

The behavior is undefined if memory areas overlap.

Example

#include <stdio.h>
#include <string.h>
int main(void)
{
    size_t n;
    char s1[10];
    char s2[10];
    printf("Please input 2 strings!\n");
    scanf("%s %s", s1, s2);
    printf("Copy how many characters?\n");
    scanf("%d", &n);
    strfill(s1, s2, n);
    /* strfill(s1, NULL, n);       Example of the transfer of s2 as a
                                   NULL pointer */
    *(s1 + n) = '\0';  /* Terminate result string with null byte */
    printf("s1 after strfill: %s\n", s1);
    printf("Current length of s1: %d\n", strlen(s1));
    return 0;
}

See also

strncpy