Skip to content

Instantly share code, notes, and snippets.

@yougg
Last active August 26, 2025 03:12
Show Gist options
  • Save yougg/e7c4ffde91ad31f0d1b23111244c2ee5 to your computer and use it in GitHub Desktop.
Save yougg/e7c4ffde91ad31f0d1b23111244c2ee5 to your computer and use it in GitHub Desktop.
ziglang simple implementation for print file tree
// zig version: 0.15.1+
const std = @import("std");
const Entry = struct {
name: []const u8,
kind: std.fs.Dir.Entry.Kind,
};
pub fn main() !void {
const allocator = std.heap.page_allocator;
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
const root = if (args.len > 1) args[1] else ".";
const out = std.fs.File.stdout();
var writer = out.writer(&.{}).interface;
try writer.print("{s}\n", .{root});
try printDirectory(allocator, root, "", &writer);
}
const indent_unicode = "│ ";
const indent_space = " ";
const suffix_last = "└──";
const suffix_mid = "├──";
fn printDirectory(allocator: std.mem.Allocator, path: []const u8, indent: []const u8, writer: *std.Io.Writer) !void {
var dir = try std.fs.cwd().openDir(path, .{ .iterate = true });
defer dir.close();
var entries = try std.ArrayList(Entry).initCapacity(allocator, 64);
defer {
for (entries.items) |entry| {
allocator.free(entry.name);
}
entries.deinit(allocator);
}
var it = dir.iterate();
while (try it.next()) |entry| {
const name_copy = try allocator.dupe(u8, entry.name);
try entries.append(allocator, Entry{
.name = name_copy,
.kind = entry.kind,
});
}
const count = entries.items.len;
for (entries.items, 0..) |entry, index| {
const is_last = index + 1 == count;
const middle = if (is_last) indent_space else indent_unicode;
const suffix = if (is_last) suffix_last else suffix_mid;
try writer.print("{s}{s} {s}\n", .{ indent, suffix, entry.name });
if (entry.kind == .directory) {
const full_len = path.len + 1 + entry.name.len;
var path_buf = try allocator.alloc(u8, full_len);
defer allocator.free(path_buf);
std.mem.copyForwards(u8, path_buf[0..path.len], path);
path_buf[path.len] = '/';
std.mem.copyForwards(u8, path_buf[path.len + 1 ..], entry.name);
const sub_path = path_buf[0..full_len];
var buf: [512]u8 = undefined;
const sub_indent = try std.fmt.bufPrint(&buf, "{s}{s}", .{ indent, middle });
try printDirectory(allocator, sub_path, sub_indent, writer);
}
}
}
@yougg
Copy link
Author

yougg commented Jul 31, 2025

zig build-exe tree.zig

./tree
.
├── .idea
│   ├── .gitignore
│   ├── libraries
│   │   └── Zig_SDK.xml
│   ├── modules.xml
│   ├── tree.iml
│   ├── workspace.xml
│   ├── ZigBrains.iml
│   └── zigbrains.xml
├── .zig-cache
│   ├── h
│   ├── o
│   │   └── f9e331f7aac48a32e9218fa9422851f7
│   └── z
│       └── 2e6d917aa7ba84914dbf9210541c5c74
├── build.zig
├── build.zig.zon
├── src
│   ├── tree.exe
│   ├── tree.exe.obj
│   ├── tree.pdb
│   └── tree.zig
└── ZigBrains.iml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment