首页 > C语言 readLine函数 处理大于缓存区字节的问题

C语言 readLine函数 处理大于缓存区字节的问题

下面给出的代码,如果在遇到换行符之前缓存就已经满了,那么该readLine函数会丢弃多余的字节,包括换行符号。所以,作为调用者,应该通过检查null之前的字符是否为换行符来判断是否有字节被丢弃。我想问的是,那么调用者知道了有字节被丢弃之后,又是如何去处理这种情况呢?

#include <unistd.h>
#include <errno.h>
#include "read_line.h"

ssize_t
read_line(int fd, void *buffer, size_t n)
{
    ssize_t numRead;    /* # of bytes fetched by last read()*/
    size_t  totRead;    /* Total bytes read so far*/
    char *buf;
    char ch;

    if (n <= 0 || buffer == NULL){
        errno = EINVAL;
        return -1;
    }

    buf = buffer;
    totRead = 0;
    for(;;){
        numRead = read(fd, &ch, 1);
        if (numRead == -1){
            if (errno == EINTR)     /*Interrupted ----> restart read()*/
                continue;
            else
                return -1;          /* some other error*/
        }else if (numRead == 0){    /* EOF*/
            if (totRead == 0)       /* No bytes read so far, return 0*/
                return 0;
            else                    /* Some bytes read so far, add '\0'*/
                break;
        }else{                      
            if (totRead < n-1){     /* Discard > (n-1) bytes */
                totRead++;
                *buf++=ch;
            }

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

    *buf = '\0';
    return totRead;
}

再调用函数读取就可以~

【热门文章】
【热门文章】