DEV Community

Cover image for You have been zigged (series) : Enumerating files and directories
Black Tornado
Black Tornado

Posted on

You have been zigged (series) : Enumerating files and directories

To open a directory for the purposes of inspecting its contents, we can use the std.Io.Dir.cwd().openDir() function. In this program, we will list out the files and directories in the mentioned directory dir_enumerator. We will not traverse sub directories for files in this program, lets save that for next.

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const my_dir = std.Io.Dir.cwd().openDir(init.io, "./dir_enumerator", .{ .access_sub_paths = false, .follow_symlinks = false, .iterate = true }) catch {
        try std.Io.File.writeStreamingAll(.stdout(), init.io, "Failed to open directory. Exiting...\n");
        std.process.exit(1);
    };
    defer my_dir.close(init.io);
    var directory_iterator = my_dir.iterate();
    var buffer: [1024]u8 = undefined;
    var file_writer = std.Io.File.Writer.init(.stdout(), init.io, &buffer);
    var stdout_printer = &file_writer.interface;

    while (directory_iterator.next(init.io) catch unreachable) |entry| {
        try stdout_printer.print("{s} - {any}\n", .{ entry.name, entry.kind });
    }
    try stdout_printer.flush();
}
Enter fullscreen mode Exit fullscreen mode

Have a dummy folder dir_enumerator and inside of it have file test1.txt, file test2.txt and sub directory subdir. Have a file subdir_file.txt inside the subdir.

The output will be

test1.txt - .file
test2.txt - .file
subdir - .directory
Enter fullscreen mode Exit fullscreen mode

Thanks for reading. To be continued.

Top comments (0)