From 2690e30a5d476cdf8689af9203748e7ed0fa841d Mon Sep 17 00:00:00 2001
From: Christian Heller <c.heller@plomlompom.de>
Date: Fri, 18 Apr 2014 14:43:20 +0200
Subject: [PATCH] Make try_fgetc() prepend clearerr() for fgetc() versions that
 need it.

---
 src/common/readwrite.c | 3 ++-
 src/common/readwrite.h | 4 +++-
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/src/common/readwrite.c b/src/common/readwrite.c
index c2c970d..045bc4f 100644
--- a/src/common/readwrite.c
+++ b/src/common/readwrite.c
@@ -4,7 +4,7 @@
 #include <stddef.h> /* size_t */
 #include <stdint.h> /* uint8_t, uint16_t, uint32_t, UINT32_MAX */
 #include <stdio.h> /* FILE, fseek(), sprintf(), fgets(), fgetc(), ferror(),
-                    * fputc(), fwrite(), fclose(), fopen()
+                    * fputc(), fwrite(), fclose(), fopen(), clearerr()
                     */
 #include <string.h> /* strlen() */
 #include <unistd.h> /* for access(), unlink() */
@@ -53,6 +53,7 @@ extern void try_fputc(uint8_t c, FILE * file, char * f)
 
 extern int try_fgetc(FILE * file, char * f)
 {
+    clearerr(file); /* OSX' (BSD?) fgetc() needs this to undo previous EOFs. */
     int test = fgetc(file);
     exit_trouble(EOF == test && ferror(file), f, "fgetc()");
     return test;
diff --git a/src/common/readwrite.h b/src/common/readwrite.h
index 4aebdbc..b61230f 100644
--- a/src/common/readwrite.h
+++ b/src/common/readwrite.h
@@ -22,7 +22,9 @@ extern void try_fputc(uint8_t c, FILE * file, char * f);
 
 /* Wrapper to calling fgetc() and fgets() from function "f". The return code is
  * returned unless ferror() indicates an error (i.e. to signify an end of file,
- * fgetc() may return an EOF and fgets() a NULL).
+ * fgetc() may return an EOF and fgets() a NULL). try_fgetc() calls clearerr()
+ * on "file" before fgetc(), because some Unixes fgetc() remember old EOFs and
+ * only return those until explicitely cleared.
  */
 extern int try_fgetc(FILE * file, char * f);
 extern char * try_fgets(char * line, int size, FILE * file, char * f);
-- 
2.30.2