gpt4 book ai didi

c - 当 snprintf 返回的值超过其大小参数时,如何获取格式化输出的最后一个字符?

转载 作者:行者123 更新时间:2023-11-30 14:42:56 26 4
gpt4 key购买 nike

我有一个长度为 65536 个字符的缓冲区。我需要将格式化输出打印到缓冲区。问题是:如果格式化的输出大小大于 65535,我希望将其最后一个字符放入缓冲区中,丢弃第一个字符,而不是剩余的字符,如 snprintf确实如此。

我考虑过实现 snprintf 逻辑,但从字符串的末尾而不是开头开始。

有没有更简单的方法来实现这一点?

最佳答案

解决方案是:

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

int snprintfEnd(char *str, size_t size, const char *format, ...)
{
va_list ap1, ap2;

va_start(ap1, format);
va_copy(ap2, ap1);

/* get length of all */
int sz = vsnprintf(0, 0, format, ap2);

va_end(ap2);

/* get all */
char * all = malloc(sz + 1);

vsprintf(all, format, ap1);
va_end(ap1);

/* copy the expected part */
int r;

if (sz < size) {
strcpy(str, all);
r = sz;
}
else {
strcpy(str, all + sz - size);
r = size;
}

free(all);
return r;
}

int main()
{
char s[6];

int ln = snprintfEnd(s, 5, "%d %d %d", 1, 234, 567);

printf("%d : '%s'\n", ln, s);

return 0;
}

执行:

5 : '4 567'

关于c - 当 snprintf 返回的值超过其大小参数时,如何获取格式化输出的最后一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54261854/

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