gpt4 book ai didi

c - strncpy() 的最佳替代方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 15:11:29 27 4
gpt4 key购买 nike

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

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

不需要像这样添加更多的代码:

buf[sizeof(buf)-1] = 0; 

最佳答案

如果你想复制的字符串长度未知,你可以使用snprintf这里。此函数将格式化输出发送到 str。它的行为类似于 sprintf(),但不会写入更多由 str 分配的字节。如果生成的字符串长于 n-1 个字符,则剩余的字符将被忽略。它还始终包含空终止符 \0,除非缓冲区大小为 0

如果您真的不想使用它,这将是 strncpy()strcpy() 的替代方法。但是,使用 strcpy() 在字符串末尾手动添加空终止符始终是一种简单、高效的方法。在 C 中,在任何已处理字符串的末尾添加空终止符是很正常的。

这是一个使用 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 结束符。

注意 strlen() 仅适用于空终止字符串,并且会导致 undefined behaviour如果字符串不是空终止的。 snprintf() 还需要更多的错误检查,可以在 man page 上找到.

正如其他人所说,这不是一种有效的方法,但如果您去寻找,它就在那里。

关于c - strncpy() 的最佳替代方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869803/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com