eaarl-io  1.0.1+71abbd4
EAARL Input/Output Library (Public API)
file_stream.c

This provides an example of how to implement a stream. The code below is the internal implementation for the standard file-based streams accessible via eaarlio_file_stream.

#include <assert.h>
#include <stdio.h>
#include "eaarlio/error.h"
#include "eaarlio/file.h"
#include "eaarlio/misc_support.h"
#include "eaarlio/stream.h"
static eaarlio_error eaarlio_file_stream_close(struct eaarlio_stream *self)
{
if(!self)
return EAARLIO_NULL;
if(!self->data)
FILE *f = (FILE *)self->data;
if(fclose(f))
}
static eaarlio_error eaarlio_file_stream_read(struct eaarlio_stream *self,
uint64_t len,
unsigned char *buf)
{
if(!self)
return EAARLIO_NULL;
if(!buf)
return EAARLIO_NULL;
if(!self->data)
if(len == 0)
FILE *f = (FILE *)self->data;
size_t bytes = fread(buf, 1, len, f);
if(ferror(f)) {
clearerr(f);
}
if(bytes < len)
assert(bytes == len);
}
static eaarlio_error eaarlio_file_stream_write(struct eaarlio_stream *self,
uint64_t len,
unsigned char const *buf)
{
if(!self)
return EAARLIO_NULL;
if(!buf)
return EAARLIO_NULL;
if(!self->data)
if(len == 0)
FILE *f = (FILE *)self->data;
size_t bytes = fwrite(buf, 1, len, f);
if(ferror(f)) {
clearerr(f);
}
if(bytes < len)
}
static eaarlio_error eaarlio_file_stream_seek(struct eaarlio_stream *self,
int64_t offset,
int whence)
{
if(!self)
return EAARLIO_NULL;
if(!self->data)
int fail = 1;
FILE *f = (FILE *)self->data;
if((long)offset != offset)
switch(whence) {
case SEEK_SET:
case SEEK_CUR:
case SEEK_END:
fail = fseek(f, (long)offset, whence);
break;
default:
}
if(fail)
}
static eaarlio_error eaarlio_file_stream_tell(struct eaarlio_stream *self,
int64_t *position)
{
if(!self)
return EAARLIO_NULL;
if(!self->data)
if(!position)
return EAARLIO_NULL;
FILE *f = (FILE *)self->data;
*position = ftell(f);
if(ferror(f)) {
clearerr(f);
}
if(*position < 0)
}
#define _EAARLIO_FILE_STREAM_BUFLEN 16
char const *fn,
char const *mode)
{
FILE *f;
if(!stream)
return EAARLIO_NULL;
*stream = eaarlio_stream_empty();
if(!fn)
return EAARLIO_NULL;
if(!mode)
return EAARLIO_NULL;
f = eaarlio_fopenb(fn, mode);
if(!f)
stream->close = &eaarlio_file_stream_close;
stream->read = &eaarlio_file_stream_read;
stream->write = &eaarlio_file_stream_write;
stream->seek = &eaarlio_file_stream_seek;
stream->tell = &eaarlio_file_stream_tell;
stream->data = (void *)f;
}