2010-12-08 61 views
0

我想知道這是否是正確的方式concatenateNUL終止包括寬度的字符串。串聯字符串和snprintf在c

#define FOO "foo" 
const char *bar = "bar"; 
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); 
+0

爲了維護目的,定義一個由`snprintf`和`sprintf`使用的格式字符串可能是個好主意。如果它在一個地方改變了,而不是另一個地方,它真的很糟糕! – 2010-12-08 03:23:19

+0

這聽起來像是一個好主意,是否可以發佈一個示例代碼參考這個?謝謝 – Lucas 2010-12-08 03:27:21

回答

0

你只需要添加1snprintf()返回的值,因爲只有一個加空終止符。

但是,您確實需要檢查l == -1(表示snprintf()失敗)。

1

很多系統在他們的標準C庫中都有一個函數asprintf,它們完全符合你在這裏所做的:allocate和sprintf