Skip to content

Commit 82da42b

Browse files
authored
os: add missing is_opened checks to File.read* functions (fix #26096) (#26413)
1 parent 37577eb commit 82da42b

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

vlib/os/file.c.v

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,9 @@ pub fn (mut f File) reopen(path string, mode string) ! {
208208

209209
// read implements the Reader interface.
210210
pub fn (f &File) read(mut buf []u8) !int {
211+
if !f.is_opened {
212+
return error_file_not_opened()
213+
}
211214
if buf.len == 0 {
212215
return Eof{}
213216
}
@@ -390,6 +393,9 @@ pub fn (f &File) read_bytes_at(size int, pos u64) []u8 {
390393
// A read call is either stopped, if the buffer is full, a newline was read or EOF.
391394
// On EOF, the method returns 0. The methods will also return any IO error encountered.
392395
pub fn (f &File) read_bytes_with_newline(mut buf []u8) !int {
396+
if !f.is_opened {
397+
return error_file_not_opened()
398+
}
393399
if buf.len == 0 {
394400
return error(@FN + ': `buf.len` == 0')
395401
}
@@ -429,6 +435,9 @@ pub fn (f &File) read_bytes_with_newline(mut buf []u8) !int {
429435
// `buf` *must* have length greater than zero.
430436
// Returns the number of read bytes, or an error.
431437
pub fn (f &File) read_bytes_into(pos u64, mut buf []u8) !int {
438+
if !f.is_opened {
439+
return error_file_not_opened()
440+
}
432441
if buf.len == 0 {
433442
return error(@FN + ': `buf.len` == 0')
434443
}
@@ -440,6 +449,9 @@ pub fn (f &File) read_bytes_into(pos u64, mut buf []u8) !int {
440449

441450
// read_from implements the RandomReader interface.
442451
pub fn (f &File) read_from(pos u64, mut buf []u8) !int {
452+
if !f.is_opened {
453+
return error_file_not_opened()
454+
}
443455
if buf.len == 0 {
444456
return 0
445457
}
@@ -451,6 +463,9 @@ pub fn (f &File) read_from(pos u64, mut buf []u8) !int {
451463
// read_into_ptr reads at most `max_size` bytes from the file and writes it into ptr.
452464
// Returns the amount of bytes read or an error.
453465
pub fn (f &File) read_into_ptr(ptr &u8, max_size int) !int {
466+
if !f.is_opened {
467+
return error_file_not_opened()
468+
}
454469
return fread(ptr, 1, max_size, f.cfile)
455470
}
456471

vlib/os/file_test.v

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,3 +518,11 @@ fn test_write_lines() {
518518
assert c1 == c2
519519
assert c1.split_into_lines() == some_lines_content.split_into_lines()
520520
}
521+
522+
fn test_read_from_closed_file() {
523+
os.write_file(tfile, 'test')!
524+
mut f := os.open(tfile)!
525+
f.close()
526+
mut buf := []u8{len: 64}
527+
assert f.read(mut buf) or { -1 } == -1
528+
}

0 commit comments

Comments
 (0)