Zig Tutorial #1

Robert Guiscard
2 min readMar 9, 2021

Zig caught my attention recently and I decided to try it. Since it is still early in the development, it would be nice to start something smaller. Let’s read a file content with zig.

After creating a directory for this project, create build.zig:

❯ zig init-exe
info: Created build.zig
info: Created src/main.zig
info: Next, try `zig build --help` or `zig build run`

You can find the main.zig under src/.

To read file, use standard library of zig like this:

const std = @import("std");
const fs = std.fs;
pub fn main() anyerror!void {
const fname = "spike.fasta";
var f = try fs.cwd().openFile(fname, fs.File.OpenFlags{ .read = true});
defer f.close();
const stdout = std.io.getStdOut().writer(); var buf: [std.mem.page_size]u8 = undefined; var bytes_read = try f.read(&buf);
while (bytes_read > 0) {
try stdout.print("{}**", .{buf[0..bytes_read]});
bytes_read = try f.read(&buf);
}
}

Zig looks like C. Many syntaxes are self explaining. The keyword try is to work with Optionals. Anything in .{} is struct.

To read line by line, use readUntilDelimiterOrEof

while (try f.reader().readUntilDelimiterOrEof(&buf, '\n')) |c| {
try stdout.print("{} **\n", .{c});
}

But if the buffer is too small, it will emit error. You need to manage memory in Zig, just like C. So be aware.

We can also use memory allocator like this:

const std = @import("std");
const fs = std.fs;
pub fn main() anyerror!void {
const fname = "spike.fasta";
var f = try fs.cwd().openFile(fname, fs.File.OpenFlags{ .read = true});
defer f.close();
const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
while (true) {
if (f.reader().readUntilDelimiterAlloc(allocator, '\n', 1024)) |c| {
try stdout.print("{} **\n", .{c});
} else |err| {
try stdout.print("== {} ==\n", .{err});
break;
}
}
}

EOF is detected throught the error.EndOfStream. And memory is allocated with ArenaAllocator. We still need to set maximal length, 1024 in this case.

There is another related post worth to read: http://ciesie.com/post/zig_learning_01/

--

--