Skip to content

std.fs.Dir.readFile "succeeds" when the buffer is too small #18880

Description

@iacore

Zig Version

0aff1f9 (latest)

Steps to Reproduce

zig/lib/std/fs/Dir.zig

Lines 1758 to 1769 in 0aff1f9

/// Read all of file contents using a preallocated buffer.
/// The returned slice has the same pointer as `buffer`. If the length matches `buffer.len`
/// the situation is ambiguous. It could either mean that the entire file was read, and
/// it exactly fits the buffer, or it could mean the buffer was not big enough for the
/// entire file.
pub fn readFile(self: Dir, file_path: []const u8, buffer: []u8) ![]u8 {
var file = try self.openFile(file_path, .{});
defer file.close();
const end_index = try file.readAll(buffer);
return buffer[0..end_index];
}

I have been shot by this footgun.

The first line of the comment of this function says

/// Read all of file contents using a preallocated buffer.

This has mislead me to believe that this is actually the case.

Expected Behavior

I had assumed that the call to this function should fail if the provided buffer is not big enough. i.e., it would read the whole file, or fail.

Observed Behavior

As it turned out, the call "succeeds" silently, returning a buffer only holding the beginning of the file.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionNo questions on the issue tracker, please.standard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions