Page 179

The standard library function int fseek(FILE *fp, long offset, int origin) is identical to lseek except that fp is a file pointer instead of a file descriptor and the return value is an int status, not a position. Write fseek. Make sure that your fseek coordinates properly with the buffering done for the other functions of the library.

#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

#define EOF (-1)
#define BUFSIZ 1024
#define OPEN_MAX 20

typedef struct _iobuf {
	int cnt; /* characters left */
	char *ptr; /* next character position */
	char *base; /* location of buffer */
	int flag; /* mode of file access */
	int fd; /* file descriptor */
} FILE;
extern FILE _iob[OPEN_MAX];

enum _flags {
	_READ = 01,
	_WRITE = 02,
	_UNBUF = 04,
	_EOF = 010,
	_ERR = 020,
};

int _flushbuf(int c, FILE *fp)
{
	int bufsize, written;

	if ((fp->flag & (_WRITE | _EOF | _ERR)) != _WRITE) {
		return EOF;
	}

	bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZ;

	if (fp->base == NULL) {
		if ((fp->base = (char *)malloc(bufsize)) == NULL) {
			return EOF;
		}
		written = 0;
	} else {
		written = write(fp->fd, fp->base, fp->ptr - fp->base);

		if (written <= 0) {
			if (written == 0) {
				fp->flag |= _EOF;
			} else {
				fp->flag |= _ERR;
			}
			fp->cnt = 0;
			return EOF;
		}
	}

	fp->ptr = fp->base;
	*fp->ptr++ = c;
	fp->cnt = bufsize - 1;
	return written;
}

int fflush(FILE *fp)
{
	if (fp == NULL) {
		for (int i = 0; i < OPEN_MAX; i++) {
			if (_iob[i].flag & _WRITE &&
			    _flushbuf(EOF, &_iob[i]) <= 0) {
				return EOF;
			}
		}
	} else if (!(fp->flag & _WRITE) || _flushbuf(EOF, fp) <= 0) {
		return EOF;
	}
	return 0;
}

/* Not tested as I don't want to bother with writing a program to read/write a text file */

int fseek(FILE *fp, long offset, int origin)
{
	if (fp->flag & _WRITE) {
		fflush(fp);
	} else if (fp->flag & _READ) {
		fp->ptr = fp->base;
		fp->cnt = fp->flag & _UNBUF ? 1 : BUFSIZ - 1;
	}
	return lseek(fp->fd, offset, origin) < 0;
}