Re: FILE* behaviour over BSD sockets - how?

From: Rich Teer (rich.teer_at_rite-group.com)
Date: 05/12/04


Date: Wed, 12 May 2004 18:32:50 GMT

On Wed, 12 May 2004, Aurelian Melinte wrote:

> The problem: I have to use a library (which I cannot modify) with an API reading/writing records to FILE*. The data I have to read comes through a socket. The socket has been set to blocking and I successfully fdopen(socket). However, the API reads once in a while incomplete records because the underlying socket calls seem to return as soon as there is a packet to read but not when the whole requested number of bytes has been read.
>
> Do not see any solution...

Use readn(), which specifically doesn't return until the requested
number of bytes has been read (unless there's an error).

Here's one version (I use tab stops of 4), from my forthcoming
book:

------------------------------------------8<---------------------------
#include <unistd.h>
#include <errno.h>

ssize_t readn (int fd, void *buf, size_t num)
{
    ssize_t res;
    size_t n;
    char *ptr;

    n = num;
    ptr = buf;
    while (n > 0) {
        if ((res = read (fd, ptr, n)) == -1) {
            if (errno == EINTR)
                res = 0;
            else
                return (-1);
        }
        else if (res == 0)
            break;

        ptr += res;
        n -= res;
    }

    return (num - n);
}
------------------------------------------8<---------------------------

Enjoy,

-- 
Rich Teer, SCNA, SCSA
President,
Rite Online Inc.
Voice: +1 (250) 979-1638
URL: http://www.rite-online.net