Last active
August 26, 2025 03:12
-
-
Save yougg/e7c4ffde91ad31f0d1b23111244c2ee5 to your computer and use it in GitHub Desktop.
ziglang simple implementation for print file tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.