What is the best alternative to strncpy()?

前端 未结 6 2158
耶瑟儿~
耶瑟儿~ 2020-12-16 20:22

The function strncpy() doesn\'t always null terminate so I want to know what is the best alternative that always null terminates? I want a function that if:

6条回答
  •  有刺的猬
    2020-12-16 21:25

    As an alternative to the answer that suggested snprintf(): (Note: trouble if n <= 0)

    size_t sz = sizeof buf;
    /*n is the number of characters to be copied from source*/
    int n = (int) sz - 1;
    snprintf(buf, sz, "%s", src);
    

    code can use the following precision:

    "... the maximum number of bytes to be written for s conversions. ..." C11 §7.21.6.1 4

    sprintf(buf, "%.*s", n, src);
    

    It has the subtle advantage in that src need not be a string, just an array of characters.

    Another tool for strings.

提交回复
热议问题