Skip to content

Commit bf6df64

Browse files
authored
feat: add IO.fgetc (#1405)
* feat: add feof and ferror These are C stdio functions that enable programmers to determine if a file read resulted in an error or EOF encounter. We can use these to power a definition of IO.fgetc, which is currently not defined. * feat: implement missing IO.fgetc IO defined a function, fgetc (distinct from IO.Raw.fgetc) which actually produced invalid code, since the name was not overridden and C does not define IO_fgetc. There was also a TODO to handle EOF conditions; so, I've implemented the function, checking for EOF and error conditions using the Raw stdio wrappers. IO.fgetc returns a Char in Success on success and an error string on failure. * refactor: distinguish EOF from errors in IO.fgetc We now report whether or not the error encountered in fgetc was EOF. Note that we don't yet report on the contents of other errors.
1 parent d2df3fe commit bf6df64

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

core/IO.carp

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,8 @@ module are wrappers around the C standard library.")
7777
(register SEEK-END Int "SEEK_END")
7878
(doc ftell "gets the position indicator of a file (thin wrapper for the C standard library).")
7979
(register ftell (Fn [(Ptr FILE)] Int) "ftell")
80+
(register feof (Fn [(Ptr FILE)] Bool) "feof")
81+
(register ferror (Fn [(Ptr FILE)] Bool) "ferror")
8082
)
8183

8284
(doc println "prints a string ref to stdout, appends a newline.")
@@ -90,7 +92,13 @@ module are wrappers around the C standard library.")
9092
(doc get-line "gets a line from stdin.")
9193
(register get-line (Fn [] String))
9294
(doc fgetc "gets a character from a file pointer (thin wrapper for the C standard library).")
93-
(register fgetc (Fn [(Ptr FILE)] Char)) ; TODO: check EOF handling (see carp_io.h)!
95+
(defn fgetc [file]
96+
(let [char (IO.Raw.fgetc file)]
97+
(if (IO.Raw.feof file)
98+
(Result.Error @"couldn't read char from file, EOF reached")
99+
(if (IO.Raw.ferror file)
100+
(Result.Error @"error while reading char from file")
101+
(Result.Success (Char.from-int char))))))
94102

95103
(doc open-file "opens a file by name using a mode (e.g. [r]ead, [w]rite, [a]ppend), [rb] read binary...). See fopen() in the C standard library for a detailed description of valid parameters.")
96104
(defn open-file [filename mode]

0 commit comments

Comments
 (0)