I’ve got a program that takes a format string from the command line which represents the format for the filenames of multiple output files. It should take just a single integer argument that can be substituted in to generate the real output filenames, and I’d like to verify that when doing my input checking. What’s a good way to determine the number of arguments a format string expects in C?
Share
The number of arguments accepted depends on the version of your C library (for example,
%aconversion specifiers were added in C99). You can be certain that it is no greater than the number of unescaped%characters (i.e., the number of%characters remaining after all%%sequences are removed) plus the number of*characters (which could be width specifiers).You should consider security issues, though; if the user supplies a
%nformat specifier this could result in a write to an arbitrary memory location. In other cases, supplying e.g.%fwould result in garbage values being output,%sin arbitrary memory contents, and even with%dspecifiers allowing the user to supply a field width e.g.%255dcould result in buffer overflow. It would be smarter to consider a different formatting scheme e.g. replacing a token (which could still be%d), but not allowing the user to supply aprintfformat string.