开发者

concatenating strings and snprintf in c

开发者 https://www.devze.com 2023-01-29 15:12 出处:网络
I\'m wondering if this is the proper way to concatenate and NUL terminate strings including width. #define FOO \"foo\"

I'm wondering if this is the proper way to concatenate and NUL terminate strings including width.

#define FOO "foo"
const char *bar = "b开发者_如何转开发ar";
int n = 10;
float f = 10.2;

char *s;
int l;

l = snprintf (NULL, 0, "%-6s %-10s %4d %4f",FOO, bar, n, f);
s = malloc (l + 4); // should it be the number of formats tags?
if (s == null) return 1;
sprintf (s, "%-6s %-10s %4d %4f", FOO, bar, n, f);


Quite a few systems have a function asprintf in their standard C libraries that does exactly what you do here: allocate and sprintf.


You only need to add 1 to the value returned by snprintf(), since there is only one null terminator added.

However, you do need to check for l == -1 (indicating that snprintf() failed).

0

精彩评论

暂无评论...
验证码 换一张
取 消