C string append

后端 未结 10 1294
野趣味
野趣味 2020-12-01 06:21

I want to append two strings. I used the following command:

new_str = strcat(str1, str2);

This command changes the value of str1

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 06:38

    Consider using the great but unknown open_memstream() function.

    FILE *open_memstream(char **ptr, size_t *sizeloc);

    Example of usage :

    // open the stream
    FILE *stream;
    char *buf;
    size_t len;
    stream = open_memstream(&buf, &len);
    
    // write what you want with fprintf() into the stream
    fprintf(stream, "Hello");
    fprintf(stream, " ");
    fprintf(stream, "%s\n", "world");
    
    // close the stream, the buffer is allocated and the size is set !
    fclose(stream);
    printf ("the result is '%s' (%d characters)\n", buf, len);
    free(buf);
    

    If you don't know in advance the length of what you want to append, this is convenient and safer than managing buffers yourself.

提交回复
热议问题