简体   繁体   English

C变量用户提供的snprintf格式字符串

[英]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. 其中所有格式字符串均由用户提供,并且将由程序使用snprintf进行更改。

the problem is if i change the occurrencess of the format strings because snprintf use a fixed value of parameters. 问题是如果我更改格式字符串的出现,因为snprintf使用参数的固定值。 - 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 如果我对文件再执行%s,则该函数确实可以正常工作,以确保原因3是最后一个snprintf有人可以提供示例代码或想法来解决此问题

note: file_buffer points to the string "hello %s %d sec ....." note: i know format strings can dangerous .. thx 注意:file_buffer指向字符串“ hello%s%d sec .....”。注意:我知道格式字符串可能很危险.. 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). 编写自己的字符串解析和插值(替换)函数,而不要使用*printf() (或使用合适的函数查找某些第三方库)。

  2. Use parse_printf_format() from glibc, which is designed to handle uses like this. 使用glibc中的parse_printf_format() ,该库旨在处理此类使用。 This is non-portable, and I don't know what other libc implementations provide similar functions. 这是不可移植的,我不知道其他哪些libc实现提供类似的功能。

Be careful though. 不过要小心。 This might be easy to get wrong and dangerous as you pointed out. 正如您指出的那样,这可能很容易出错并且很危险。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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