Skip to content

Commit

Permalink
Add a read-line function (Issue #97).
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
eholk committed May 5, 2015
1 parent ccf9e97 commit adfba0d
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions lib/harlan/io.kfc
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down
10 changes: 10 additions & 0 deletions rt/builtin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
8 changes: 6 additions & 2 deletions test/read-file.kfc
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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)))

1 change: 1 addition & 0 deletions test/read-file.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
44
3.141592654
hello
this is a line

0 comments on commit adfba0d

Please sign in to comment.