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:
parent
8c04b5fe9c
commit
2e1da4b4bc
31
vlib/os/os.v
31
vlib/os/os.v
@ -162,29 +162,44 @@ pub fn mv(old, new string) {
|
|||||||
// TODO return `?[]string` TODO implement `?[]` support
|
// TODO return `?[]string` TODO implement `?[]` support
|
||||||
pub fn read_lines(path string) []string {
|
pub fn read_lines(path string) []string {
|
||||||
mut res := []string
|
mut res := []string
|
||||||
mut buf := [1000]byte
|
mut buf_len := 1024
|
||||||
|
mut buf := malloc(buf_len)
|
||||||
|
|
||||||
mode := 'rb'
|
mode := 'rb'
|
||||||
mut fp := &C.FILE{}
|
mut fp := &C.FILE{}
|
||||||
$if windows {
|
$if windows {
|
||||||
fp = C._wfopen(path.to_wide(), mode.to_wide())
|
fp = C._wfopen(path.to_wide(), mode.to_wide())
|
||||||
} $else {
|
} $else {
|
||||||
cpath := path.str
|
fp = C.fopen(path.str, mode.str)
|
||||||
fp = C.fopen(cpath, mode.str)
|
|
||||||
}
|
}
|
||||||
if isnil(fp) {
|
if isnil(fp) {
|
||||||
// TODO
|
// TODO
|
||||||
// return error('failed to open file "$path"')
|
// return error('failed to open file "$path"')
|
||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
for C.fgets(buf, 1000, fp) != 0 {
|
|
||||||
mut val := ''
|
mut buf_index := 0
|
||||||
buf[C.strlen(buf) - 1] = `\0` // eat the newline fgets() stores
|
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 windows {
|
||||||
if buf[strlen(buf)-2] == 13 {
|
if buf[len - 2] == 13 {
|
||||||
buf[strlen(buf) - 2] = `\0`
|
buf[len - 2] = `\0`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
res << tos_clone(buf)
|
res << tos_clone(buf)
|
||||||
|
buf_index = 0
|
||||||
}
|
}
|
||||||
C.fclose(fp)
|
C.fclose(fp)
|
||||||
return res
|
return res
|
||||||
|
Loading…
Reference in New Issue
Block a user