read扩展 健壮地读--有缓冲

代码:
#include < stdio.h>
#include < fcntl.h>
#include < unistd.h>
#include < sys/types.h>
#include < sys/uio.h>
#include < string.h>

typedef struct{
int rio_fd;
int rio_cnt;
char *rio_bufptr;
char rio_buf[8192];
} rio_t;

void rio_readinitb(rio_t *rp,int fd);
ssize_t rio_read(rio_t *rp,char *usrbuf,size_t n);
ssize_t rio_readlineb(rio_t *rp,void *usrbuf,size_t maxlen);

int main(){
int fd;
char buf[1000];
rio_t fd2;
fd =open(“a.txt”,’r’);
if(fd <=0) { printf("open file error!"); return 0; } rio_readinitb(&fd2,fd); if(rio_readlineb(&fd2,buf,8192) >0)
{
printf(“file information:%s!\n”,buf);
}

close(fd);

}

void rio_readinitb(rio_t *rp,int fd){
rp->rio_fd = fd;
rp->rio_cnt = 0;
rp->rio_bufptr = rp->rio_buf;
}

ssize_t rio_read(rio_t *rp,char *usrbuf,size_t n){
int cnt;

while(rp->rio_cnt <=0){ rp->rio_cnt = read(rp->rio_fd,rp->rio_buf,sizeof(rp->rio_buf));
if(rp->rio_cnt <0) { return -1; }else if(rp->rio_cnt ==0)
return 0;
else
rp->rio_bufptr = rp->rio_buf;
}

cnt = n;
if(rp->rio_cnt rio_cnt;
}

memcpy(usrbuf,rp->rio_bufptr,cnt); //缓冲方法

rp->rio_bufptr +=cnt;
rp->rio_cnt -=cnt;

return cnt;

}

ssize_t rio_readlineb(rio_t *rp,void *usrbuf,size_t maxlen){
int n,rc;
char c,*bufp = usrbuf;

for(n=1 ; n < maxlen ;n++){ if(( rc = rio_read(rp,&c,1))==1){ *bufp++ =c; if( c =='\n'){ break; }else if(rc ==0){ if(n==1){ return 0; }else break; } }else{ return -1; } } *bufp =0; return n; }