Created
April 21, 2026 19:06
-
-
Save habedi/f1d65434047518c345c0137738eee2df to your computer and use it in GitHub Desktop.
Reading from a text file in Zig `0.17.0-dev.56+a8226cd53`
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
| // This is `file.zig` | |
| // Run: ~/.local/share/zig/0.17.0-dev.56+a8226cd53/zig run file.zig | |
| const std = @import("std"); | |
| pub fn main(init: std.process.Init.Minimal) !void { | |
| // Set up a general-purpose allocator. | |
| var debug_allocator: std.heap.DebugAllocator(.{}) = .init; | |
| defer _ = debug_allocator.deinit(); | |
| const gpa = debug_allocator.allocator(); | |
| // Set up the threaded I/O backend and get an `Io` handle | |
| var threaded: std.Io.Threaded = .init(gpa, .{ | |
| .argv0 = .init(init.args), | |
| .environ = init.environ, | |
| }); | |
| defer threaded.deinit(); | |
| const io = threaded.io(); | |
| // Set up stdout with the Writer interface | |
| var stdout_buffer: [1024]u8 = undefined; | |
| var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer); | |
| const stdout = &stdout_writer.interface; | |
| // Open the file read-only in the current working directory | |
| var file = try std.Io.Dir.cwd().openFile(io, "file.zig", .{ .mode = .read_only }); | |
| defer file.close(io); | |
| // Read chunk by chunk until EOF and print each chunk | |
| var read_buf: [1024]u8 = undefined; | |
| var file_reader = file.reader(io, &read_buf); | |
| const reader = &file_reader.interface; | |
| while (true) { | |
| var chunk: [256]u8 = undefined; | |
| const n = try reader.readSliceShort(&chunk); | |
| if (n == 0) break; | |
| try stdout.print("{s}", .{chunk[0..n]}); | |
| } | |
| try stdout.flush(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment