fileiozig

How to read a file to a byte array in Zig


How to read a file to a byte array in Zig?

I'd like to read the contents of a file to byte array in Zig.

I have a path to the file and I'd like to read contents of the file to a single contiguous byte array. The file is so small that it will fit comfortably in memory.


Solution

  • This first fetches the size of the file and uses that as max_size for readToEndAlloc. This assumes that the size of the file stays constant, that is, it doesn't change while you run this code.

    const file = try std.fs.cwd().openFile(path, .{});
    defer file.close();
    
    const stat = try file.stat();
    const buf: []u8 = try file.readToEndAlloc(allocator, stat.size);
    

    Tested with Zig 0.13.0 in December 2024.