sockets/read_line_buf.c

This is sockets/read_line_buf.c, an example to accompany the book, The Linux Programming Interface.

This file is not printed in the book; it is the solution to Exercise 59-1:a (page 1236).

The source code file is copyright 2022, Michael Kerrisk, and is licensed under the GNU Lesser General Public License, version 3.

In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.

 

Download sockets/read_line_buf.c

  Cover of The Linux Programming Interface

Function list (Bold in this list means a function is not static)

/* read_line_buf.c

   Implementation of readLineBuf(), a version of readLine() that is more
   efficient because it reads blocks of characters at a time.
*/
#include <unistd.h>
#include <errno.h>
#include "read_line_buf.h"
void                    /* Initialize a ReadLineBuf structure */
readLineBufInit(int fd, struct ReadLineBuf *rlbuf)
{
    rlbuf->fd = fd;
    rlbuf->len = 0;
    rlbuf->next = 0;
}
/* Return a line of input from the buffer 'rlbuf', placing the characters in
   'buffer'. The 'n' argument specifies the size of 'buffer'. If the line of
   input is larger than this, then the excess characters are discarded. */

ssize_t
readLineBuf(struct ReadLineBuf *rlbuf, char *buffer, size_t n)
{
    if (n <= 0 || buffer == NULL) {
        errno = EINVAL;
        return -1;
    }

    size_t cnt = 0;

    /* Fetch characters from rlbuf->buf, up to the next new line. */

    for (;;) {

        /* If there are insufficient characters in 'tlbuf', then obtain
           further input from the associated file descriptor. */

        if (rlbuf->next >= rlbuf->len) {
            rlbuf->len = read(rlbuf->fd, rlbuf->buf, RL_MAX_BUF);
            if (rlbuf->len == -1)
                return -1;

            if (rlbuf->len == 0)        /* End of file */
                break;

            rlbuf->next = 0;
        }

        char c = rlbuf->buf[rlbuf->next];
        rlbuf->next++;

        if (cnt < n)
            buffer[cnt++] = c;

        if (c == '\n')
            break;
    }

    return cnt;
}

 

Download sockets/read_line_buf.c

Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.

Valid XHTML 1.1