Skip to content

Commit 2d8a136

Browse files
authored
os: fix file read (#10247)
1 parent 1555716 commit 2d8a136

File tree

2 files changed

+6
-6
lines changed

2 files changed

+6
-6
lines changed

vlib/os/fd.c.v

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ pub fn fd_read(fd int, maxbytes int) (string, int) {
4949
return '', 0
5050
}
5151
unsafe {
52-
mut buf := malloc(maxbytes)
52+
mut buf := malloc(maxbytes + 1)
5353
nbytes := C.read(fd, buf, maxbytes)
5454
if nbytes < 0 {
5555
free(buf)

vlib/os/os_c.v

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -110,14 +110,14 @@ pub fn read_file(path string) ?string {
110110
C.rewind(fp)
111111
unsafe {
112112
mut str := malloc(fsize + 1)
113-
nelements := int(C.fread(str, fsize, 1, fp))
113+
nelements := int(C.fread(str, 1, fsize, fp))
114114
is_eof := int(C.feof(fp))
115115
is_error := int(C.ferror(fp))
116116
if is_eof == 0 && is_error != 0 {
117117
free(str)
118118
return error('fread failed')
119119
}
120-
str[fsize] = 0
120+
str[nelements] = 0
121121
if nelements == 0 {
122122
// It is highly likely that the file was a virtual file from
123123
// /sys or /proc, with information generated on the fly, so
@@ -129,7 +129,7 @@ pub fn read_file(path string) ?string {
129129
// get a V string with .len = 4096 and .str = "PCH\n\\000".
130130
return str.vstring()
131131
}
132-
return str.vstring_with_len(fsize)
132+
return str.vstring_with_len(nelements)
133133
}
134134
}
135135

@@ -586,13 +586,13 @@ pub fn read_file_array<T>(path string) []T {
586586
// read the actual data from the file
587587
len := fsize / tsize
588588
buf := unsafe { malloc(fsize) }
589-
C.fread(buf, fsize, 1, fp)
589+
nread := C.fread(buf, tsize, len, fp)
590590
C.fclose(fp)
591591
return unsafe {
592592
array{
593593
element_size: tsize
594594
data: buf
595-
len: len
595+
len: int(nread)
596596
cap: len
597597
}
598598
}

0 commit comments

Comments
 (0)