每个字符串参数的长度 [英] Length of each string argument
问题描述
最近我开始对 stdarg.h
函数有所了解,因为我想要一些类似于 printf
的东西,而不是写到控制台我想将它作为字符串返回.
Recently I've started to get a little bit into the stdarg.h
functions, because I want to have something similar to printf
but instead of writing to the console I want to return it as a string.
到目前为止,我的想法是:
Here's what I've come up with so far:
char *write(const char *format, ...)
{
// init
va_list arg;
char *string;
va_start (arg, format);
vsprintf (string, format, arg);
// done
va_end (arg);
return string;
}
现在的问题是,string
没有保留内存,这就是我需要帮助来修复此功能的地方,因为我还没有找到任何解决方案.
Now the problem is, that string
has not reserved memory and that's where I need help with a way to fix this function as I have not found any solution yet.
提前致谢
推荐答案
使用 snprintf(NULL, 0
来检查你需要多长的缓冲区.然后分配内存.然后打印到字符串.>
Use snprintf(NULL, 0
to check how long buffer you need. Then allocate memory. Then print to the string.
char *my_write(const char *format, ...) {
va_list va;
va_start(va, format);
// remember to have a separate va_list for each v*print function
va_list va2;
va_copy(va2, va);
const int len = vsnprintf(NULL, 0, format, va2);
va_end(va2);
char *string = malloc((len + 1) * sizeof(*string));
if (string != NULL) {
vsprintf(string, format, va);
}
va_end(va);
return string;
}
正如@IanAbbott 在评论中所建议的,您可以调用 va_start
两次,这似乎很好地简化了代码:
As suggested by @IanAbbott in comments you can invoke va_start
twice, which seems to nicely simplify the code:
char *my_write(const char *format, ...) {
va_list va;
va_start(va, format);
const int len = vsnprintf(NULL, 0, format, va);
va_end(va);
char *string = malloc((len + 1) * sizeof(*string));
if (string == NULL) {
return NULL;
}
va_start(va, format);
vsprintf(string, format, va);
va_end(va);
return string;
}
在带有 glibc 的平台上,您还可以使用 vasprintf
.请注意,名称 write
已被 使用posix write() 函数,我建议使用不同的名称.使用 vasprintf
GNU 扩展,它变成了:
On platforms with with glibc you can also use vasprintf
. Note that the name write
is already used by posix write() function, I suggest to use a different name. With vasprintf
GNU extension it becomes just:
#define _GNU_SOURCE
#include <stdio.h>
char *write2(const char *format, ...) {
va_list va;
va_start(va, format);
char *string;
const int err = vasprintf(&string, format, va);
va_end(va);
if (err == -1) {
return NULL;
}
return string;
}
这篇关于每个字符串参数的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!