使用C预处理器构造scanf的字符串文字? [英] Using C preprocessor to construct a string literal for scanf?

查看:113
本文介绍了使用C预处理器构造scanf的字符串文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建 sscanf 字符串文字,以帮助防止C99中的缓冲区溢出。目标如下:

I'm attempting to create an sscanf string literal to aid in buffer overrun prevention in C99. The goal is something like:

#define MAX_ARG_LEN   16

char arg[MAX_ARG_LEN] = "";

if (sscanf(arg, "%"(MAX_ARG_LEN-1)"X", &input) > 0)

显而易见的手动解决方案如下:

The obvious "manual" solution is something like:

#define MAX_ARG_LEN   16
#define MAX_ARG_CHARS "15"

char arg[MAX_ARG_LEN] = "";

if (sscanf(arg, "%"MAX_ARG_CHARS"X", &input) > 0)

但是,在缓冲区大小为16的情况下,我希望自动生成%15X。此链接对于我的应用程序来说几乎是 将预处理器令牌转换为字符串,但不处理-1。

However, I would prefer something to automatically generate "%15X" given a buffer size of 16. This link is almost works for my application: Convert a preprocessor token to a string but it does not handle the -1.

建议?

推荐答案

Kernighan和Pike在他们(出色)的书'编程实践'并得出结论,最可靠,最可移植的方法是使用 sprintf( )生成格式字符串。

Kernighan and Pike discuss this issue in their (excellent) book 'The Practice of Programming' and concluded that the most reliable and portable way to do this is to use sprintf() to generate the format string.

您可以做的就是将宏定义为不包含终端null的长度,然后像这样使用:

What you could do is define the macro as the length excluding terminal null, and then use that like this:

#define STR_EVALUATE(x)   #x
#define STRINGIFY(x)      STR_EVALUATE(x)
#define MAX_ARG_LEN 15
char arg[MAX_ARG_LEN+1] = "";

if (sscanf(arg, "%" STRINGIFY(MAX_ARG_LEN) "X", &input) > 0)
    ...

或者您可以将MAX_ARG_STRLEN定义为15,将MAX_ARG_LEN定义为MAX_ARG_STRLEN + 1并相应地工作。

Or you could define MAX_ARG_STRLEN as 15 and MAX_ARG_LEN as MAX_ARG_STRLEN+1 and work accordingly.

这篇关于使用C预处理器构造scanf的字符串文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆