os: fix file read (#10247)

pull/10261/head
Uwe Krüger 2021-05-29 15:53:42 +02:00 committed by GitHub
parent 15557161cc
commit 2d8a136d6e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 6 deletions

View File

@ -49,7 +49,7 @@ pub fn fd_read(fd int, maxbytes int) (string, int) {
return '', 0 return '', 0
} }
unsafe { unsafe {
mut buf := malloc(maxbytes) mut buf := malloc(maxbytes + 1)
nbytes := C.read(fd, buf, maxbytes) nbytes := C.read(fd, buf, maxbytes)
if nbytes < 0 { if nbytes < 0 {
free(buf) free(buf)

View File

@ -110,14 +110,14 @@ pub fn read_file(path string) ?string {
C.rewind(fp) C.rewind(fp)
unsafe { unsafe {
mut str := malloc(fsize + 1) 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_eof := int(C.feof(fp))
is_error := int(C.ferror(fp)) is_error := int(C.ferror(fp))
if is_eof == 0 && is_error != 0 { if is_eof == 0 && is_error != 0 {
free(str) free(str)
return error('fread failed') return error('fread failed')
} }
str[fsize] = 0 str[nelements] = 0
if nelements == 0 { if nelements == 0 {
// It is highly likely that the file was a virtual file from // It is highly likely that the file was a virtual file from
// /sys or /proc, with information generated on the fly, so // /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". // get a V string with .len = 4096 and .str = "PCH\n\\000".
return str.vstring() return str.vstring()
} }
return str.vstring_with_len(fsize) return str.vstring_with_len(nelements)
} }
} }
@ -586,13 +586,13 @@ pub fn read_file_array<T>(path string) []T {
// read the actual data from the file // read the actual data from the file
len := fsize / tsize len := fsize / tsize
buf := unsafe { malloc(fsize) } buf := unsafe { malloc(fsize) }
C.fread(buf, fsize, 1, fp) nread := C.fread(buf, tsize, len, fp)
C.fclose(fp) C.fclose(fp)
return unsafe { return unsafe {
array{ array{
element_size: tsize element_size: tsize
data: buf data: buf
len: len len: int(nread)
cap: len cap: len
} }
} }