From 6f32cbdea312a760b97956786aafb2fff78d2b29 Mon Sep 17 00:00:00 2001 From: Yuichi Nishiwaki Date: Thu, 16 Jan 2014 19:56:45 +0900 Subject: [PATCH] handle end-of-file while reading file object --- include/picrin/port.h | 5 +++++ src/port.c | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/include/picrin/port.h b/include/picrin/port.h index 4d12d6e7..67a5b277 100644 --- a/include/picrin/port.h +++ b/include/picrin/port.h @@ -17,7 +17,12 @@ enum pic_port_status { #define PIC_UBUFSIZ 3 +enum pic_file_flags { + PIC_FILE_EOF = 1, +}; + typedef struct { + short flags; /* buffered IO */ char *buf; int mode; diff --git a/src/port.c b/src/port.c index f894eb54..09cebf73 100644 --- a/src/port.c +++ b/src/port.c @@ -72,6 +72,7 @@ pic_fflush(pic_file *file) int r; r = file->vtable.write(file->vtable.cookie, file->s, file->c - file->s); + /* TODO: error handling (r == -1 or r < file->c - file->s)*/ file->c -= r; return r; } @@ -82,6 +83,10 @@ pic_ffill(pic_file *file) int r; r = file->vtable.read(file->vtable.cookie, file->c, file->e - file->c); + /* TODO: error handling (r == -1) */ + if (r < file->e - file->c) { + file->flags |= PIC_FILE_EOF; + } file->c += r; return r; } @@ -194,9 +199,14 @@ pic_fread(void *ptr, size_t block, size_t nitems, pic_file *file) file->c = file->s; size -= avail; dst += avail; + if ((file->flags & PIC_FILE_EOF) != 0) + break; pic_ffill(file); } } + /* handle end-of-file */ + *dst = EOF; + return block * nitems - size; } size_t