Using C preprocessor to construct a string literal for scanf?
- by Brett
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)
However, I would prefer something to automatically generate "%15X" given a buffer size of 16. This link is almost works for my application: http://stackoverflow.com/questions/240353/convert-a-preprocessor-token-to-a-string but it does not handle the -1.
Suggestions?