how to push the received bytes to std::list?

mc 4,436 Reputation points
2024-08-06T15:51:50.06+00:00

how to push the received bytes?

I do not how many bytes I will receive and when to use them so can I use std::list<char> buffer?

char buf[3096]={0};
while(true){
memset(buf,0,3096);
int bytes=recv(socket,buf,3096);

//here how to push the buf to buffer?
}

I may use this later.

if I do not use std::list I have to free char array and re-create them. right?

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,693 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 53,971 Reputation points
    2024-08-06T16:32:18.9766667+00:00

    That is what the std:list:assign function is for.

    buffer.assign(buf, buf+bytes);
    

    That will replace the existing contents though. If you want to add to the existing list then AFAIK C++ doesn't provide a way to do that for an array but a simple iteration loop works.

    for (int index = 0; index < bytes; ++index)
       buffer.push_back(buf[index]);
    

    Note that insert might work here with an array, never tried it. It has the same overload as assign so you could pass the start and end of the array to it along with the position to insert (the end of the list) and see what happens.

    As for whether you should be using std:list or not though that is dependent on what you're trying to do. In terms of asking

    if I do not use std::list I have to free char array and re-create them. right?

    No you don't have to, but you might want to depending on what you're doing. If you want to allocate your buf and the 3K size limit is sufficient for your message then you can use that single buffer to read data until you reach the limit. All you would need to do is call recv again but pass the address of the element where you want the next batch of data to be inserted. Perhaps something like this, not tested.

    char buf[3096]={0};
    int bufferSize = sizeof(buf);
    char* position = buf;
    
    while(true) {   
       int bytes=recv(socket, buf, bufferSize);
       position += bytes;
       bufferSize -= bytes;
    
       if (bufferSize <= 0) {
        // Ran out of space, now what?
       };   
    
       //Whatever logic to determine if you need to read again
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.