如何对printf存储到一个变量? [英] how to store printf into a variable?

查看:193
本文介绍了如何对printf存储到一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用类似的东西来存储格式化字符串的printf什么做用C

I want to store a formatted string using something similar to what printf does in C.

char *tmp = (char *)sqlite3_column_text(selectstmt, 2);
const char *sqlAnswers = printf("select key from answer WHERE key = %s LIMIT 5;", tmp);

下面是明显的错误,我的C ++程序员肯定很多在那里会给我这个快速解答,感谢adavance。

The following is an error obviously, I am sure alot of c programmers out there would give me a quick answer for this, thanks in adavance.

推荐答案

您可以用的sprintf 做,但不是单独(安全)。在一个健全的系统,使用的snprintf 两次,一次是找出使用的大小和第二次真正做到这一点。这取决于的snprintf 返回所需的字符数,当它运行的空间。 Linux的,BSD和C99兼容的系统做到这一点; Windows通常可以没有。在后一种情况下,你需要分配初始缓冲并分配一个更大的,如果的snprintf 失败(在一个循环,直到的snprintf 成功)。但在C99,下面的工作:

You can do it with sprintf, but not alone (safely). On a sane system, use snprintf twice, once to find out the size to use and the second time to actually do it. This depends on snprintf returning the number of characters needed when it runs out of room. Linux, BSD, and C99-compatible systems do this; Windows typically does not. In the latter case, you'll need to allocate an initial buffer and allocate a bigger one if snprintf fails (in a loop until snprintf succeeds). But on C99, the following will work:

char *buf;
size_t sz;
sz = snprintf(NULL, 0, "select key from answer WHERE key = %s LIMIT 5;", tmp);
buf = (char *)malloc(sz + 1); /* make sure you check for != NULL in real code */
snprintf(buf, sz+1, "select key from answer WHERE key = %s LIMIT 5;", tmp);

然而,为构建SQL,它远远不如使用 prepared语句。他们避免SQL注入漏洞(频繁的sprintf 需要)。有了他们,你会prepare的声明,从答案中选择key其中key =限制5;?,然后用参数 TMP 执行。 SQL引擎把字符串中并删除需要确保它正确转义第一。

However, for building SQL, it's far better to use prepared statements. They avoid SQL injection vulnerabilities (and frequently the need for sprintf). With them, you would prepare the statement "select key from answer where key = ? limit 5;", and then execute it with the parameter tmp. The SQL engine puts in the string and removes the need to make sure it's properly escaped first.

这篇关于如何对printf存储到一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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