c - 如何将 printf 存储到变量中?

标签 c string string-formatting

我想使用类似于 printf 在 C 中所做的事情来存储格式化字符串。

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

后者显然是一个错误。

最佳答案

您可以使用 sprintf 来完成,但不能单独使用(安全)。在一个健全的系统上,使用 snprintf 两次,一次是找出要使用的大小,第二次是实际使用。这取决于 snprintf 在空间不足时返回所需的字符数。 Linux、BSD 和 C99 兼容系统执行此操作; Windows 通常不会。在后一种情况下,您需要分配一个初始缓冲区并在 snprintf 失败时分配一个更大的缓冲区(在循环中直到 snprintf 成功)。但在 C99 上,以下将起作用:

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 statements .它们避免了 SQL 注入(inject)漏洞(通常需要 sprintf)。使用它们,您将准备语句“select key from answer where key = ? limit 5;”,然后使用参数 tmp 执行它。 SQL 引擎放入字符串并消除了确保它首先被正确转义的需要。

关于c - 如何将 printf 存储到变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1745726/

相关文章:

c - 如何使用 ASSERT 检查字符串是否包含字符?

+= 和 << 连接字符串的 Ruby 区别

c# - 如何在没有科学表示的情况下格式化 XAML 中的 double 值以在末尾删除零?

c# - 如何在 Asp.net 中将 SqlDataReader 字符串格式化为货币格式?

c - "Multiple definition of X"C 程序错误

c - 为什么我得不到 "Segmentation Fault"?

c++ - SendInput() 键盘字母 C/C++

c# - .NET 字符串真的应该被认为是不可变的吗?

c++ - 使用指针替换cpp中字符串中的字符

c# - 在 C# 中使用 {#} 打印整数?