c里面的printf, fprintf, sprintf, snprintf, printf_s, fprintf_s, sprintf_s, snprintf_s一问说清所有各种printf

都定义在<stdio.h>中,有些事C99的一部分,有些事C11新加的。如下:

int printfconst char*          format, ... );
(until C99)
int printfconst charrestrict format, ... );
(since C99)
  (2)  
int fprintfFILE*          stream, const char*          format, ... );
(until C99)
int fprintfFILErestrict stream, const charrestrict format, ... );
(since C99)
  (3)  
int sprintfchar*          buffer, const char*          format, ... );
(until C99)
int sprintfcharrestrict buffer, const charrestrict format, ... );
(since C99)
int snprintfcharrestrict buffer, size_t bufsz,
              const charrestrict format, ... );
(4) (since C99)
int printf_sconst charrestrict format, ... );
(5) (since C11)
int fprintf_sFILErestrict stream, const charrestrict format, ... );
(6) (since C11)
int sprintf_scharrestrict buffer, rsize_t bufsz,
               const charrestrict format, ... );
(7) (since C11)
int snprintf_scharrestrict buffer, rsize_t bufsz,
                const charrestrict format, ... );
(8) (since C11)

各个gcc编译器版本对c标准的支持情况参见这里

规则为:普通的printf就是打印,sprintf就是格式化用途、叫做messageformat更合适。fprintf就是指定流而不是使用stdout标准流。带n版本为指定长度。带s的版本为所谓的安全版。

所以简单一点,格式化就用snprintf,写文件就用fprintf。

对应printf还有wprintf,vprintf,w\v代替f。w是宽字符。v版本和非v版本的区别在于,v版本自己管理可变参数。如下:

The functions vprintf(), vfprintf(), vdprintf(), vsprintf(),
       vsnprintf() are equivalent to the functions printf(), fprintf(),
       dprintf(), sprintf(), snprintf(), respectively, except that they
       are called with a va_list instead of a variable number of
       arguments.  These functions do not call the va_end macro.
       Because they invoke the va_arg macro, the value of ap is
       undefined after the call.

带_s是所谓的安全版本,c11标准的一部分,会检查参数,由宏__STDC_WANT_LIB_EXT1__控制。参见https://software-dl.ti.com/codegen/docs/tiarmclang/compiler_tools_user_guide/compiler_manual/compiler_security/C11_secure_functions.html,https://docs.oracle.com/cd/E88353_01/html/E37843/snprintf-s-3c.html

参考:https://en.cppreference.com/w/c/io/fprintf

https://www.man7.org/linux/man-pages/man3/vsnprintf.3.html

posted @   zhjh256  阅读(77)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2022-10-19 LightDB 22.3与龙芯LoongArch完成认证适配
2021-10-19 lightdb/postgresql pg_control文件的作用
2019-10-19 mysql 8.0.18 hash join测试(内外网首文)
2019-10-19 Hash算法及java HashMap底层实现原理理解(含jdk 1.7以及jdk 1.8)
2019-10-19 Hash冲突的线性探测开放地址法
2019-10-19 zookeeper acl认证机制及dubbo、kafka集成、zooviewer/idea zk插件配置
2019-10-19 CAS单点登录源码解析之【客户端】
点击右上角即可分享
微信分享提示