Search code examples
c++http-redirectstreambinaryfwrite

fwrite Binary Stream to char array or string


    size = recvfrom(sockfd, buf, BUF_SIZE, 0, (struct sockaddr *)&src, &srclen);
    /*stuff*/
    fwrite(buf, size, 1, stdout);

I obtain a message using recvfrom() and am able to output to stdout via fwrite, but I need to store the data that I am currently just outputting to the console. What's the best method for doing this?


Solution

  • As the binary data may contain nulls, you can't use usual string conversion or c-string functions (risk of partial copy). The solution would be to:

    char *pbuf = new char[size]; 
    if (pbuf) 
       std::copy(buf, buf+size, pbuf);  
    // then store the pointer somewhere
    

    It uses std::copy(), which takes the begin and end of the reginon to copy it, so it's appropriate for binary data.