C 中的 snprintf 与 strcpy(等) [英] snprintf vs. strcpy (etc.) in C
问题描述
为了进行字符串连接,我一直在做 char* 缓冲区的基本 strcpy
、strncpy
.然后我了解了 snprintf
和朋友.
For doing string concatenation, I've been doing basic strcpy
, strncpy
of char* buffers. Then I learned about the snprintf
and friends.
我是否应该坚持使用 strcpy
、strcpy
+ \0
终止?或者我将来应该只使用 snprintf
吗?
Should I stick with my strcpy
, strcpy
+ \0
termination? Or should I just use snprintf
in the future?
推荐答案
在大多数情况下,我怀疑使用 strncpy
和 snprintf
是可衡量的.
For most purposes I doubt the difference between using strncpy
and snprintf
is measurable.
如果涉及任何格式,我倾向于只使用 snprintf
而不是混合在 strncpy
中.
If there's any formatting involved I tend to stick to only snprintf
rather than mixing in strncpy
as well.
我发现这有助于代码清晰,这意味着您可以使用以下习语来跟踪您在缓冲区中的位置(从而避免创建 Shlemiel the Painter 算法):
I find this helps code clarity, and means you can use the following idiom to keep track of where you are in the buffer (thus avoiding creating a Shlemiel the Painter algorithm):
char sBuffer[iBufferSize];
char* pCursor = sBuffer;
pCursor += snprintf(pCursor, sizeof(sBuffer) - (pCursor - sBuffer), "some stuff\n");
for(int i = 0; i < 10; i++)
{
pCursor += snprintf(pCursor, sizeof(sBuffer) - (pCursor - sBuffer), " iter %d\n", i);
}
pCursor += snprintf(pCursor, sizeof(sBuffer) - (pCursor - sBuffer), "into a string\n");
这篇关于C 中的 snprintf 与 strcpy(等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!