约 1052 字

约 5 分钟

#C 语言标准库函数 sprintf

#include <stdio.h>

int sprintf(char *restrict s, const char *restrict format, ...);

说明

按格式向字节数组写出数据。

按照格式说明提供参数,转换以当前 locale 的相应规则为准。

调用方须确保数组足以容纳结果和终止符。输出量可能变化时可使用 snprintf。

自 C89 起提供。

参数

  • s - 接收输出的可写字节数组。
  • format - 以空字符结束的格式串,包含普通字符和转换指令。
  • ... - 随转换指令提供的输出值。

返回值

  • 正常返回实际写出字节数,排除终止符。输出或编码错误时返回负值。

#示例

#include <stdio.h>

int main(void)
{
    char text[32];
    int count = sprintf(text, "item %d\n", 42);
    return count != 8;
}

#相关接口

#参考标准

更新: 2026/11/28

作者: planc

创建: 2026/11/28