Concatenating char buffer into a string

后端 未结 2 703
醉话见心
醉话见心 2021-01-25 22:45

In the following snippet, I receive the data until I have completely received all the data from the socket client. I keep on storing the data in a char buffer of size 300.

2条回答
  •  情歌与酒
    2021-01-25 23:34

    You can do this something like the following. I assume that buffer does not contain a string.

    ssize_t b;
    char buffer[300]
    size_t n = 1;
    char *s = calloc( 1, sizeof( char ) );
    
    while((b = recv(socket_fd,buffer,sizeof(buffer))) > 0) {
    
        char *tmp = realloc( s, b + n );
    
        if ( !tmp )
        {
            // report an error
            break;
        }
    
        s = tmp;
        memcpy( s + n - 1, buffer, b );
        n += b;
        s[n - 1] = '\0';  
    }
    

提交回复
热议问题