简体   繁体   中英

C variable user supplied format strings for snprintf

i want to for example make a file like this

hello %s
%d seconds more
%d is more than %d

where all the format strings are user supplied and will be changed by the program with snprintf.

the problem is if i change the occurrencess of the format strings because snprintf use a fixed value of parameters. - the last parameters ...

to understand my idea thats how i want it for example

snprintf(dest_buffer, strlen(file_buffer), file_buffer, "user123", 1, 3, 2);

if i do one more %s to the file the functions doesent work correctly for sure cause 3 was last arg to snprintf can someone provide sample code or ideas to solve this problem

note: file_buffer points to the string "hello %s %d sec ....." note: i know format strings can dangerous .. thx

There's two alternatives that I can think of:

  1. Write your own string parsing and interpolation (replacement) functions instead of using *printf() (or hunt down some third-party library with suitable functions).

  2. Use parse_printf_format() from glibc, which is designed to handle uses like this. This is non-portable, and I don't know what other libc implementations provide similar functions.

Be careful though. This might be easy to get wrong and dangerous as you pointed out. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM