在 C 中查找格式化字符串的长度

Sri*_*nth 1 c strlen

我的应用程序中有以下功能:

 void func(char *file, int line)
 {
    char stmt[150];
    sprintf(stmt, "Failed in file %s, at line number %d", file, line);
 }
Run Code Online (Sandbox Code Playgroud)

在这里,我采用 150 字节的字符数组(粗略猜测),而不是我需要找到我在 sprintf() 中给出的字符串的长度并采用该大小的数组。

请建议我是否在 C 中使用这种工具来查找格式化字符串的长度。谢谢 !

Lub*_*lář 6

怎么样snprintf?该函数不会写入比给定数字更多的字符,而是返回如果它有足够的空间它将创建的字符串的长度。

 int len = snprintf(NULL, 0, "Failed in file %s, at line number %d", file, line);
Run Code Online (Sandbox Code Playgroud)