How to read a file in comptime outside a src dir

Can I compile my program with a extern file content? Something like:
const myContent = comptime readMyFile() catch …;

I tried and got this:

C:\Users\nicol\AppData\Roaming\Code\User\globalStorage\ziglang.vscode-zig\zig_install\lib\std\fs.zig:258:36: note: called from here
        return .{ .fd = windows.peb().ProcessParameters.CurrentDirectory.Handle };
src\main.zig:5:32: note: called from here
    const file = try std.fs.cwd().openFile("./client/dist/bundle.js", .{});
src\main.zig:12:35: note: called from here
    const JS = comptime readBundle(std.heap.page_allocator) catch {

Obviously the error is trying to read a cwd file, but I don’t know if the problem would be using cwd or creating the file, and if it is creating the file, would there be another way to compile the contents of another file along with my code?

Have you seen @embedFile?


I already tried using it but I wasn’t sure if it was the correct function, I’ll try it more thoroughly, thanks

This is a solution, but I’ve a question. @embedFile looks can’t read files outside src dir, it’s bad

I believe you can add an import in your build.zig although I’ve never done this. Maybe someone else knows.

I’ve tried this:

// build.zig

nothing different

Ok, I think you need to do this:

// build.zig
    exe.root_module.addAnonymousImport("myfile", .{
        .root_source_file = b.path("assets/myfile.txt"),

I believe addIncludePath is purely for C interop.
Side note, don’t use LazyPath.relative, use b.path instead.


working now, thanks broo!

1 Like