--- /sys/include/bio.h +++ /sys/include/bio.h @@ -58,6 +58,7 @@ int Binits(Biobufhdr*, int, int, uchar*, int); int Blinelen(Biobufhdr*); vlong Boffset(Biobufhdr*); Biobuf* Bopen(char*, int); +Biobuf* Bfdopen(int, int); int Bprint(Biobufhdr*, char*, ...); int Bvprint(Biobufhdr*, char*, va_list); int Bputc(Biobufhdr*, int); --- /sys/man/2/bio +++ /sys/man/2/bio @@ -1,6 +1,6 @@ .TH BIO 2 .SH NAME -Bopen, Binit, Binits, Brdline, Brdstr, Bgetc, Bgetrune, Bgetd, Bungetc, Bungetrune, Bread, Bseek, Boffset, Bfildes, Blinelen, Bputc, Bputrune, Bprint, Bvprint, Bwrite, Bflush, Bterm, Bbuffered \- buffered input/output +Bopen, Bfdopen, Binit, Binits, Brdline, Brdstr, Bgetc, Bgetrune, Bgetd, Bungetc, Bungetrune, Bread, Bseek, Boffset, Bfildes, Blinelen, Bputc, Bputrune, Bprint, Bvprint, Bwrite, Bflush, Bterm, Bbuffered \- buffered input/output .SH SYNOPSIS .ta \w'Biobuf* 'u .B #include @@ -13,6 +13,9 @@ Bopen, Binit, Binits, Brdline, Brdstr, Bgetc, Bgetrune, Bgetd, Bungetc, Bungetru Biobuf* Bopen(char *file, int mode) .PP .B +Biobuf* Bfdopen(int fd, int mode) +.PP +.B int Binit(Biobuf *bp, int fd, int mode) .PP .B @@ -93,6 +96,17 @@ It calls .IR malloc (2) to allocate a buffer. .PP +.I Bfdopen +allocates a buffer for the already-open file descriptor +.I fd +for mode +.B OREAD +or +.BR OWRITE . +It calls +.IR malloc (2) +to allocate a buffer. +.PP .I Binit initializes a standard size buffer, type .IR Biobuf , @@ -138,7 +152,9 @@ and returns .IR Bflush 's return value. If the buffer was allocated by -.IR Bopen , +.I Bopen +or +.IR Bfdopen , the buffer is .I freed and the file is closed. --- /sys/src/libbio/binit.c +++ /sys/src/libbio/binit.c @@ -93,6 +93,22 @@ Binit(Biobuf *bp, int f, int mode) return Binits(bp, f, mode, bp->b, sizeof(bp->b)); } +Biobuf* +Bfdopen(int f, int mode) +{ + Biobuf *bp; + + bp = malloc(sizeof(Biobuf)); + if(bp == 0) + return 0; + if(Binits(bp, f, mode, bp->b, sizeof(bp->b)) != 0){ + free(bp); + return 0; + } + bp->flag = Bmagic; /* mark bp open & malloced */ + return bp; +} + Biobuf* Bopen(char *name, int mode) { @@ -112,9 +128,9 @@ Bopen(char *name, int mode) } if(f < 0) return 0; - bp = malloc(sizeof(Biobuf)); - Binits(bp, f, mode, bp->b, sizeof(bp->b)); - bp->flag = Bmagic; /* mark bp open & malloced */ + bp = Bfdopen(f, mode); + if(bp == 0) + close(f); return bp; }