How to use std.fs.cwd().readFile()?

Hi guys, Zig noob here, wondering how can/should I use the readFile from stdlib. The compiler lets me write the following, but it results on empty bytes and empty result, though:

const bytes: []u8 = undefined;
const result = try std.fs.cwd().readFile(filename, bytes);

std.log.info("bytes: {any}", .{bytes});
std.log.info("result: {any}", .{result});
info: bytes: {  }
info: result: {  }

I thought I could specify the byte length, but zig doesn’t like it:

const bytes: [2048]u8 = undefined;
error: expected type '[]u8', found '[2048]u8'

Any help is appreciated, thanks!

You are almost there. You need to specify a slice with capacity as Zig won’t allocate for you. Or if you don’t know the size beforehand, use the readFileAlloc method with an allocator.
You also need to understand slices and arrays in Zig (see here).

Then if you do this, it will work:

// make the array writable by defining it as a var not a const
var bytes: [1<<16]u8 = undefined;
// use the array address to turn it into a slice
const result = try std.fs.cwd().readFile(filename, &bytes);

std.log.info("bytes: {any}", .{bytes});
std.log.info("result: {any}", .{result});
2 Likes

One little improvement

const std = @import("std");

pub fn main() !void {
    var buf: [1024]u8 = undefined;
    const filename = "build.zig";
    // use the array address to turn it into a slice
    const result = try std.fs.cwd().readFile(filename, &buf);

    std.log.info("result: {s}", .{result});
    std.log.info("bytes: {s}", .{buf[0..result.len]});
}

FYI, readFile is just a wrapper of readAll

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];
}
2 Likes