将char缓冲区串联为字符串 [英] Concatenating char buffer into a string

查看:69
本文介绍了将char缓冲区串联为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码段中,我将接收数据,直到完全从套接字客户端接收到所有数据为止.我继续将数据存储在大小为300的char缓冲区中.

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.

ssize_t b;
char buffer[300]
while((b = recv(socket_fd,buffer,sizeof(buffer))) > 0) {
   // keep on receiving the data

}

但是问题出在每次迭代中,缓冲区重新装满,旧值丢失.如何将缓冲区值连接为一个,以便在循环结束时将消息作为一个完整的字符串得到?

But the problem is on each iteration, buffer gets refilled and old values are lost. How do I concatenate the buffer values into one, so that at the end of the loop I get the message as one complete string?

推荐答案

您可以执行以下操作.我认为缓冲区不包含字符串.

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';  
}

这篇关于将char缓冲区串联为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆