zig

How do I get the full path of a `std.fs.Dir`?


Is there any way to access the full path of a std.fs.Dir struct? I've looked through all of the methods in the source but I can't find anything that gets path-related information on the directory.


Solution

  • Zig recommends against getting the absolute path of a file/directory, and is considering removing the ability from the standard library: https://github.com/ziglang/zig/issues/19353

    Until then:

    One option is realpath

    const std = @import("std");
    
    pub fn main() !void {
        var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
        defer arena.deinit();
        const alloc = arena.allocator();
    
        std.log.info("cwd: {s}", .{
            try std.fs.cwd().realpathAlloc(alloc, "."),
        });
    }
    

    realpath internally calls std.os.getFdPath and there doesn't seem to be any function on Dir that just does that right now.