Iterate read () from socket

Is this the right way to iterate over readin a socket? I can hardly get it to work correctly. data.sizeis that unsigned intwhich is also populated from the socket. Right. data.datais unsigned char *.

if ( data.size > 0 ) {
    data.data = (unsigned char*)malloc(data.size);
    memset(&data.data, 0, data.size);
    int remainingSize = data.size;
    unsigned char *iter = data.data;
    int count = 0;
    do {
        count = read(connect_fd, iter, remainingSize);
        iter += count;
        remainingSize -= count;
    } while (count > 0 && remainingSize > 0);
}
else {
    data.data = 0;
}

Thanks in advance.

+3
source share
4 answers

You need to check the return value from reading before you start adding it to other values.

You will get zero when the socket reports EOF and -1 on error. Keep in mind that for a socket, EOF does not match private.

+9
source

while.

while((remainingSize > 0) && (count = read(connect_fd, iter, remainingSize)) > 0)
{
    iter += count;
    remainingSize -= count;
}

, , .
, , .

:
, .

malloc ( ) . std::vector. , , , .

, data.data, std::vector < unsigned char >

if ( data.size > 0 )
{
    std::vector<unsigned char>   buffer(data.size);

    unsigned char *iter = &buffer[0];
    while(...  read(connect_fd, iter, remainingSize) )
    {
        .....
    }

    ... handle error as required

    buffer.resize(buffer.size() - remainingSize);
    data.data.swap(buffer);
}
+3

, read() - , , , -, . .

, BSD C, - - FIONREAD ioctl(), , ( , - -, select()), (), , , .

+3

Source: https://habr.com/ru/post/1706211/


All Articles