Struggling to simply read from a file?

It would be helpful to see the panic message, othewise I will be guessing just based on the code.

My guess is that you are getting an assert triggered because of aliasing. You are mixing up the uses of the different buffers.
In the code example you provided, you are using the same buffer for both the reader interface and the destination buffer. This is likely the cause of your problem.
There are a few ways around this:

Use the internal buffer directly

You can access the reader’s internal buffer and fill it using methods on the Reader. Calling fillMore will fill the buffer and then you can access the buffer from the Reader with buffered

Read into another buffer

You can create 2 buffers and use them:

    var buffer: [1024]u8 = undefined;
    const file_reader = file.reader(&buffer);
    var reader = file_reader.interface;
    var copy_buffer = [1024]u8 = undefined;
    try reader.readSliceAll(&copy_buffer);
    std.debug.print("{s}\n", .{&copy_buffer});

Note: The buffers can be different sizes

Stream into a Writer

This is a more special use case, but if you are wanting to read the whole file into a new allocated buffer, you can use Writer.Allocating and stream from the reader using Reader.stream. You could also used a Fixed Allocator as well if you don’t want allocation but want to fill a bigger buffer.

1 Like