1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
   | #include <sys/errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "bio.h"
BFILE *bopen(const char *filename, const char *mode)
{
	BFILE *stream;
	int flags;
	int fd;
	char md;
	
	if (strcmp(mode,"r") == 0) {
		flags = O_RDONLY;
		md = BMODE_READ;
	} else {
		errno = EINVAL;
		return NULL;
	}
	if ((fd = open(filename, flags, PERM_FILE)) == -1)
		return NULL;
	if ((stream=(BFILE *)malloc(sizeof(BFILE)))!=NULL) {
		stream->fd=fd;
		stream->mode=md;
		stream->pos=0;
	}
	return stream;
}
ssize_t bread(void *buf, ssize_t size, BFILE *stream)
{
	char *ptr;
	ssize_t more;
	if ((stream==NULL)||(stream->mode!=BMODE_READ)) {
		errno = EBADF;
		return 0;
	}
	more=size;
	ptr=buf;
	while (stream->fill-stream->pos < more) {
		memcpy(ptr,&stream->buf[stream->pos],stream->fill-stream->pos);
		ptr+=stream->fill-stream->pos;
		stream->pos=0;
		if ((stream->fill=read(stream->fd,stream->buf,BBUFSIZ))<=0) {
			stream->eof=(stream->fill==0);
			stream->fill=0;
			return size-more;
		}
	}
	memcpy(ptr,&stream->buf[stream->pos],more);
	stream->pos+=more;
	return size;
}
int beof(BFILE *stream)
{
	return stream->eof;
}
int bclose(BFILE *stream)
{
	int r;
	
	if (stream==NULL) {
		errno = EBADF;
		return BEOF;
	}
	if ((r=close(stream->fd))==0)
		free(stream);
	return r;
} | 
Partager