稍微不同的方法:
void zap(char **stmt, char *argument, size_t *stmtBufLen)
{
char *fmt="INSERT INTO test(nazwa, liczba) VALUES ('nowy wpis', '%s')";
/**
* Is our current buffer size (stmtBufLen) big enough to hold the result string?
*/
size_t newStmtLen = strlen(fmt) + strlen(argument) - 2;
if (*stmtBufLen < newStmtLen)
{
/**
* No. Extend the buffer to accomodate the new statement length.
*/
char *tmp = realloc(*stmt, newStmtLen + 1);
if (tmp)
{
*stmt = tmp;
*stmtLen = newStmtLen+1;
}
else
{
/**
* For now, just write an error message to stderr; the statement
* buffer and statement length are left unchanged.
*/
fprintf(stderr, "realloc failed; stmt was not modified\n");
return;
}
}
/**
* Write statement with argument to buffer.
*/
sprintf(*stmt, fmt, argument);
}
int main(void)
{
char *stmtBuffer = NULL;
size_t stmtBufferLen = 0;
...
zap(&stmtBuffer, "foo", &stmtBufferLen);
...
zap(&stmtBuffer, "blurga", &stmtBufferLen);
...
zap(&stmtBuffer, "AReallyLongArgumentName", &stmtBufferLen);
...
zap(&stmtBuffer, "AnEvenLongerRidiculouslyLongArgumentName", &stmtBufferLen);
...
free(stmtBuffer);
return 0;
}
此版本使用動態存儲器分配根據需要來調整緩衝器,具有NULL緩衝器指針開始(realloc的(NULL,大小)==的malloc(大小) )。這樣你就不必擔心從一個「足夠大」的緩衝區開始。唯一的缺點是你需要記住當你完成緩衝區時釋放緩衝區(我通常不喜歡這樣分配調用者和被調用者之間的內存管理職責;如果我考慮了超過10分鐘,拿出更好的東西)。
看來你正在與數據庫交互。你必須使用純粹的C?另外,大多數DB都有API來安全地構建SQL語句。你可以使用這些嗎? – kennytm
謝謝,是的 - 我使用MySQL C API,但我必須創建一個字符串用作查詢,因爲我不能在查詢本身中使用變量。 – Devel