@@ -188,7 +188,42 @@ VAL idris_strlen(VM* vm, VAL l) {
188188 return MKINT((i_int)(strlen(GETSTR(l))));
189189}
190190
191+#define BUFSIZE 256
192+
191193VAL idris_readStr(VM* vm, FILE* h) {
194+// Modified from 'safe-fgets.c' in the gdb distribution.
195+// (see http://www.gnu.org/software/gdb/current/)
196+ char *line_ptr;
197+ char* line_buf = (char *) malloc (BUFSIZE);
198+ int line_buf_size = BUFSIZE;
199+
200+ /* points to last byte */
201+ line_ptr = line_buf + line_buf_size - 1;
202+
203+ /* so we can see if fgets put a 0 there */
204+ *line_ptr = 1;
205+ if (fgets (line_buf, line_buf_size, h) == 0)
206+ return MKSTR(vm, "");
207+
208+ /* we filled the buffer? */
209+ while (line_ptr[0] == 0 && line_ptr[-1] != '\n')
210+ {
211+ /* Make the buffer bigger and read more of the line */
212+ line_buf_size += BUFSIZE;
213+ line_buf = (char *) realloc (line_buf, line_buf_size);
214+
215+ /* points to last byte again */
216+ line_ptr = line_buf + line_buf_size - 1;
217+ /* so we can see if fgets put a 0 there */
218+ *line_ptr = 1;
219+
220+ if (fgets (line_buf + line_buf_size - BUFSIZE - 1, BUFSIZE + 1, h) == 0)
221+ return MKSTR(vm, "");
222+ }
223+
224+ VAL str = MKSTR(vm, line_buf);
225+ free(line_buf);
226+ return str;
192227}
193228
194229