Search code examples
cstringprintf

snprintf vs. strcpy (etc.) in C


For doing string concatenation, I've been doing basic strcpy, strncpy of char* buffers. Then I learned about the snprintf and friends.

Should I stick with my strcpy, strcpy + \0 termination? Or should I just use snprintf in the future?


Solution

  • For most purposes I doubt the difference between using strncpy and snprintf is measurable.

    If there's any formatting involved I tend to stick to only snprintf rather than mixing in strncpy as well.

    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");