snprintf vs. strcpy (etc.) in C

后端 未结 7 1811
长发绾君心
长发绾君心 2021-01-02 07:35

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

7条回答
  •  醉话见心
    2021-01-02 08:21

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

提交回复
热议问题