From 2d8a136d6ebab1b6e88e88fdcc8d8a692688af06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Uwe=20Kr=C3=BCger?= <45282134+UweKrueger@users.noreply.github.com> Date: Sat, 29 May 2021 15:53:42 +0200 Subject: [PATCH] os: fix file read (#10247) --- vlib/os/fd.c.v | 2 +- vlib/os/os_c.v | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/vlib/os/fd.c.v b/vlib/os/fd.c.v index 8eeb1a2d33..1bb59fd836 100644 --- a/vlib/os/fd.c.v +++ b/vlib/os/fd.c.v @@ -49,7 +49,7 @@ pub fn fd_read(fd int, maxbytes int) (string, int) { return '', 0 } unsafe { - mut buf := malloc(maxbytes) + mut buf := malloc(maxbytes + 1) nbytes := C.read(fd, buf, maxbytes) if nbytes < 0 { free(buf) diff --git a/vlib/os/os_c.v b/vlib/os/os_c.v index 8740789815..cce104ada5 100644 --- a/vlib/os/os_c.v +++ b/vlib/os/os_c.v @@ -110,14 +110,14 @@ pub fn read_file(path string) ?string { C.rewind(fp) unsafe { mut str := malloc(fsize + 1) - nelements := int(C.fread(str, fsize, 1, fp)) + nelements := int(C.fread(str, 1, fsize, fp)) is_eof := int(C.feof(fp)) is_error := int(C.ferror(fp)) if is_eof == 0 && is_error != 0 { free(str) return error('fread failed') } - str[fsize] = 0 + str[nelements] = 0 if nelements == 0 { // It is highly likely that the file was a virtual file from // /sys or /proc, with information generated on the fly, so @@ -129,7 +129,7 @@ pub fn read_file(path string) ?string { // get a V string with .len = 4096 and .str = "PCH\n\\000". return str.vstring() } - return str.vstring_with_len(fsize) + return str.vstring_with_len(nelements) } } @@ -586,13 +586,13 @@ pub fn read_file_array(path string) []T { // read the actual data from the file len := fsize / tsize buf := unsafe { malloc(fsize) } - C.fread(buf, fsize, 1, fp) + nread := C.fread(buf, tsize, len, fp) C.fclose(fp) return unsafe { array{ element_size: tsize data: buf - len: len + len: int(nread) cap: len } }