zoukankan      html  css  js  c++  java
  • sprintf_s的使用

    int sprintf_s(char *restrict buffer, rsize_t bufsz,
                  const char *restrict format, ...);

    将数据格式化输出到字符串,sprintf_s()是sprintf()的安全版本,通过指定缓冲区长度来避免sprintf()存在的溢出风险。

    sprintf_s原先只有windows的编译器才只支持,并不是C中的标准函数。

    在C11标准中加入了对该函数的支持,但是是可选的,并非强制加入。

    C11中规定,如果编译器实现了__STDC_LIB_EXT1__ 宏,那么就要支持对该函数的实现。

    gcc编译器只是部分的支持C11标准,本人测试在ubuntu的gcc 5.4.0版本中也没有实现__STDC_LIB_EXT1__ 。

    gcc中可以用snprintf函数简单替代sprintf_s,但是注意2者在实现上是有一定的区别,不是完全相同。

    int snprintfchar *restrict buffer, int bufsz, 
                  const char *restrict format, ... );

    C11原文如下:

    __STDC_LIB_EXT1__ The integer constant 201ymmL, intended to indicate support
    for the extensions defined in annex K (Bounds-checking interfaces).
    Implementations that do not define __STDC_LIB_EXT1__ are not required to conform to these
    specifications.

    C++网站给出的使用建议如下:

    As all bounds-checked functions, printf_sfprintf_ssprintf_s, and snrintf_s 

    are only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation

    and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including <stdio.h>.

      

    参考用法如下:

    #if defined(__STDC_LIB_EXT1__)
      #if (__STDC_LIB_EXT1__ >= 201112L)
        #define __STDC_WANT_LIB_EXT1__ 1 /* Want the ext1 functions */
      #endif
    #endif
    
    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>
    
    #if (__STDC_WANT_LIB_EXT1__ == 1)
      char tempArray[20];
      sprintf_s(tempArray, 20, "Int %d", 1);
    #endif

     Windows的中用法如下:

    #if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION)
        sprintf_s(...)
    #else
        sprintf(...)
    #endif
  • 相关阅读:
    Unity3d修炼之路:游戏开发中,3d数学知识的练习【1】(不断更新.......)
    Codeforces 463C Gargari and Bishops 题解
    kettle入门(七) 之kettle增量方案(一)全量比对取增量-依据唯一标示
    cpp学习笔记 1一个简单的小程序以及一些的知识点
    POJ 1321-棋盘问题(DFS)
    偶遇 smon 进程cpu 开销高异常分析
    Android 虚线切割线
    magento安装wordpress
    分组password算法
    Android_编程规范与经常使用技巧
  • 原文地址:https://www.cnblogs.com/dirt2/p/6104198.html
Copyright © 2011-2022 走看看