1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

Merge pull request #1050 from avitkauskas/fix-read-lines

os: fix read_lines
This commit is contained in:
Alvydas Vitkauskas 2019-07-31 11:56:36 +03:00 committed by Alexander Medvednikov
parent 8c04b5fe9c
commit 2e1da4b4bc

View File

@ -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