zoukankan      html  css  js  c++  java
  • C++ 安全字符串拼接

     1 #include <stdio.h>
     2 #include <stdint.h>
     3 #include <stdarg.h>
     4 
     5 #if defined(__GNUC__)
     6 #endif
     7 
     8 #if defined(_MSC_VER)
     9 #define snprintf(buf,size,fmt,...) sprintf_s(buf,size,fmt,__VA_ARGS__)
    10 #define vsnprintf(buf,size,fmt,...) vsprintf_s(buf,size,fmt,__VA_ARGS__)
    11 #endif
    12 
    13 #define STRAPPEND(buf, size, offset, fmt, ...) do { 
    14 if (offset < size) 
    15     { 
    16     offset += snprintf(buf + offset, size - offset, fmt, __VA_ARGS__); 
    17     }
    18 }while (0)
    19 
    20 
    21 inline void StrAppend(char buf[], const uint32_t bufLen, uint32_t &offset, const char *fmt, ...)
    22 {
    23     va_list argptr;
    24     va_start(argptr, fmt);
    25     if (offset < bufLen)
    26     {
    27         offset += vsnprintf(buf + offset, bufLen - offset, fmt, argptr);
    28     }
    29     va_end(argptr);
    30 }
    31 
    32 int32_t main(int32_t argc, char *argv[])
    33 {
    34     char buf[64] = { 0 };
    35     uint32_t offset = 0;
    36     StrAppend(buf, 64, offset, "%d ", 12);
    37     StrAppend(buf, 64, offset, ",%s--", "qwe");
    38     StrAppend(buf, 64, offset, ",%0.2f!!!", 1.0);
    39     printf("%s
    ", buf);
    40     offset = 0;
    41     STRAPPEND(buf, 64, offset, "%d ", 121);
    42     STRAPPEND(buf, 64, offset, ",%s--", "qwe1");
    43     STRAPPEND(buf, 64, offset, ",%0.3f!!!", 11.0);
    44     printf("%s
    ", buf);
    45     return 0;
    46 }
  • 相关阅读:
    websocket的理解及实例应用
    laravel框架cookie应用到中间件的理解
    PHP多机实现session共享
    mysql中exists的详细说明
    window环境下安装pear
    php 进程管理及操作
    PHP设计模式之职责链模式
    PHP设计模式之备忘录模式
    PHP设计模式之装饰模式
    PHP设计模式之策略模式
  • 原文地址:https://www.cnblogs.com/tangxin-blog/p/5604116.html
Copyright © 2011-2022 走看看