From adfba0d78b18c08e8e0ec3a876e04b63a4454fa8 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Tue, 5 May 2015 12:04:02 -0400 Subject: [PATCH] Add a read-line function (Issue #97). This reads a line of text from a file as a string. The returned string includes the trailing newline character. This leaks memory too, because strings are not region-allocated (Issue #149) --- lib/harlan/io.kfc | 1 + rt/builtin.cpp | 10 ++++++++++ test/read-file.kfc | 8 ++++++-- test/read-file.txt | 1 + 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/harlan/io.kfc b/lib/harlan/io.kfc index 1c4217b..c1f3b96 100644 --- a/lib/harlan/io.kfc +++ b/lib/harlan/io.kfc @@ -9,6 +9,7 @@ (extern hscanf-float ((ptr FILE) str (ptr float)) -> int) (extern hscanfu64 ((ptr FILE) (ptr u64)) -> int) (extern hgets ((ptr FILE)) -> str) + (extern file-read-line ((ptr FILE)) -> str) (define (file-open name) (fopen name "r")) diff --git a/rt/builtin.cpp b/rt/builtin.cpp index 384d05b..188fa57 100644 --- a/rt/builtin.cpp +++ b/rt/builtin.cpp @@ -155,6 +155,16 @@ char* hgets(FILE *f) { return new_str; } +// This will leake memory (#149) +char *file$dread$dline(FILE *f) { + char *buf = NULL; + size_t size = 0; + + getline(&buf, &size, f); + + return buf; +} + void flush$dstdout() { cout.flush(); } diff --git a/test/read-file.kfc b/test/read-file.kfc index 1cc7e2b..62d57db 100644 --- a/test/read-file.kfc +++ b/test/read-file.kfc @@ -11,7 +11,10 @@ (i (file-read-int f)) (u (file-read-u64 f)) (flt (file-read-float f)) - (s (file-read-string f))) + (s (file-read-string f)) + (line (file-read-line f)) ;; We have to read to the end of + ;; the previous line. + (line (file-read-line f))) (fclose f) (println i) (assert (= i 42)) @@ -21,5 +24,6 @@ (assert (< (h-abs (- flt 3.141592654)) 0.000000001)) (println* "'" s "'") (assert (= s "hello")) + (println* "'" line "'") + (assert (= line "this is a line\n")) 0))) - diff --git a/test/read-file.txt b/test/read-file.txt index 23f447f..b28e6d7 100644 --- a/test/read-file.txt +++ b/test/read-file.txt @@ -2,3 +2,4 @@ 44 3.141592654 hello +this is a line