Iterate directory

There is a convenient method walk for this purpose, it will walk the directory iteratively.

const std = @import("std");
const fs = std.fs;
const print = std.debug.print;

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer if (gpa.deinit() != .ok) @panic("leak");
    const allocator = gpa.allocator();

    // In order to walk the directry, `iterate` must be set to true.
    var dir = try fs.cwd().openDir("zig-out", .{ .iterate = true });
    defer dir.close();

    var walker = try dir.walk(allocator);
    defer walker.deinit();

    while (try walker.next()) |entry| {
        print("path: {s}, basename:{s}, type:{s}\n", .{
            entry.path,
            entry.basename,
            @tagName(entry.kind),
        });
    }
}

The order of returned file system entries is undefined, if there are any requirements for the order in which to return the entries, such as alphabetical or chronological, sort them accordingly. Otherwise, leave them in their original, unsorted order.

Last change: 2025-01-04, commit: e2f845a