什么是strncpy()的最佳替代品? [英] What is the best alternative to strncpy()?

查看:165
本文介绍了什么是strncpy()的最佳替代品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数strncpy()并不总是以null终止,所以我想知道始终以null终止的最佳替代方法是什么? 我想要一个函数,如果:

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; 

推荐答案

如果您要复制的字符串的长度未知,则可以使用

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 \0, unless the buffer size is 0.

如果您真的不想使用它,则它可以替代strncpy()strcpy().但是,使用strcpy()手动在字符串末尾添加空终止符始终是一种简单而有效的方法.在C语言中,在任何已处理字符串的末尾添加一个空终止符是很正常的.

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.

以下是使用sprintf()的基本示例:

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\n", str, strlen(str));

    return 0;
}

哪个打印出来:

String = Hello World, Length = 11

此示例显示snprintf()通过"Hello World"复制到str,并在末尾添加了\0终止符.

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

注意: strlen()仅适用于以null终止的字符串,并且会导致手册页中找到.

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.

这篇关于什么是strncpy()的最佳替代品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆