Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

c - What is the best alternative to strncpy()?

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:

strlen(src) >= n /*n is the number of characters to be copied from source*/

there's no need to add further code like this:

buf[sizeof(buf)-1] = 0; 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If the length of the string you desire to copy is unknown, you can use snprintf here. This function sends formatted output to str. It acts similarily to sprintf(), but instead does not write more bytes allocated by str. If the resulting string is longer than n-1 characters, then the remaining characters are left out. It also always includes the null terminator , unless the buffer size is 0.

This would be a alternative to strncpy() or strcpy(), if you really don't want to use it. However, manually adding a null terminator at the end of your string with strcpy() is always a simple, efficient approach. It is very normal in C to add a null terminator at the end of any processed string.

Here is a basic example of using sprintf():

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

#define SIZE 1024

int main(void) {
    const size_t N = SIZE;
    char str[N];
    const char *example = "Hello World";

    snprintf(str, sizeof(str), "%s", example);

    printf("String = %s, Length = %zu
", str, strlen(str));

    return 0;
}

Which prints out:

String = Hello World, Length = 11

This example shows that snprintf() copied over "Hello World" into str, and also added a terminator at the end.

Note: strlen() only works on null terminated strings, and will cause undefined behaviour if the string is not null terminated. snprintf() also needs more error checking, which can be found on the man page.

As others have said, this is not an efficient approach, but it is there if you go looking.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...