From 2e1da4b4bc3e9655e19bf6128ff68a24380a13f9 Mon Sep 17 00:00:00 2001 From: Alvydas Vitkauskas Date: Wed, 31 Jul 2019 11:56:36 +0300 Subject: [PATCH] Merge pull request #1050 from avitkauskas/fix-read-lines os: fix read_lines --- vlib/os/os.v | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/vlib/os/os.v b/vlib/os/os.v index c1d27347c3..06a9e0993f 100644 --- a/vlib/os/os.v +++ b/vlib/os/os.v @@ -162,29 +162,44 @@ pub fn mv(old, new string) { // TODO return `?[]string` TODO implement `?[]` support pub fn read_lines(path string) []string { mut res := []string - mut buf := [1000]byte + mut buf_len := 1024 + mut buf := malloc(buf_len) + mode := 'rb' mut fp := &C.FILE{} $if windows { fp = C._wfopen(path.to_wide(), mode.to_wide()) } $else { - cpath := path.str - fp = C.fopen(cpath, mode.str) + fp = C.fopen(path.str, mode.str) } if isnil(fp) { // TODO // return error('failed to open file "$path"') return res } - for C.fgets(buf, 1000, fp) != 0 { - mut val := '' - buf[C.strlen(buf) - 1] = `\0` // eat the newline fgets() stores + + mut buf_index := 0 + for C.fgets(buf + buf_index, buf_len - buf_index, fp) != 0 { + len := C.strlen(buf) + if len == buf_len - 1 && buf[len - 1] != 10 { + buf_len *= 2 + buf = C.realloc(buf, buf_len) + if isnil(buf) { + panic('Could not reallocate the read buffer') + } + buf_index = len + continue + } + if buf[len - 1] == 10 { + buf[len - 1] = `\0` + } $if windows { - if buf[strlen(buf)-2] == 13 { - buf[strlen(buf) - 2] = `\0` + if buf[len - 2] == 13 { + buf[len - 2] = `\0` } } res << tos_clone(buf) + buf_index = 0 } C.fclose(fp) return res