Skip to content

Zig File I/O

Sooner or later every program wants to save something: settings, a log, results, a to-do list. This page covers files and folders in Zig 0.17: writing and reading a whole file in one call, opening files yourself for bigger jobs, appending, reading line by line, handling a file that isn’t there, and making, listing and deleting folders. Every example here really writes to disk and cleans up after itself, so you can run them as they are.

In Zig you don’t open files by a bare path. You ask a folder (a std.Io.Dir) to open a file inside it. Most of the time that folder is the current working directory, the folder your terminal is in when you start the program:

const cwd = std.Io.Dir.cwd();

Two things to keep in mind:

  • Relative paths like "notes.txt" are relative to where you run the program, not where its source file lives. Run it from another folder and it reads and writes there.
  • Every file operation takes io, the std.Io value from init.io. Files are outside the program, so they go through the same I/O interface as stdout (Zig Io Interface explains why).

For small files, there’s a one-call version of each direction:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa = init.gpa;
const cwd = std.Io.Dir.cwd();
try cwd.writeFile(io, .{ .sub_path = "hello.txt", .data = "Hello, file!\nSecond line.\n" });
const text = try cwd.readFileAlloc(io, "hello.txt", gpa, .limited(1024 * 1024));
defer gpa.free(text);
std.debug.print("{d} bytes:\n{s}", .{ text.len, text });
try cwd.deleteFile(io, "hello.txt");
}

Output:

26 bytes:
Hello, file!
Second line.
  • writeFile creates the file, or replaces everything in it if it already exists. It takes its options as a struct: .sub_path is the file name, .data is what to write.
  • readFileAlloc reads the whole file into freshly allocated memory and gives you a []u8. You own that memory, so defer gpa.free(text) right away.
  • .limited(1024 * 1024) is a safety limit. If the file is bigger, you get error.StreamTooLong instead of your program trying to load a 10 GB file into memory by accident.
  • deleteFile removes it, so this example leaves nothing behind.

The most common file error by far is error.FileNotFound. Often it isn’t really an error at all: no settings file just means “use the defaults”. Catch that one error and pass the rest up:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa = init.gpa;
const cwd = std.Io.Dir.cwd();
const text = cwd.readFileAlloc(io, "settings.txt", gpa, .limited(64 * 1024)) catch |err| switch (err) {
error.FileNotFound => {
std.debug.print("no settings.txt, using defaults\n", .{});
return;
},
else => return err,
};
defer gpa.free(text);
std.debug.print("settings: {s}\n", .{text});
}

Output:

no settings.txt, using defaults

catch |err| switch (err) handles each error its own way, which the reference calls switching on errors. Other errors you’ll meet with files:

Error Usually means
FileNotFound The file, or a folder in its path, doesn’t exist.
AccessDenied / PermissionDenied You’re not allowed to read or write it.
IsDir You tried to read a folder as if it were a file.
PathAlreadyExists You asked to create something that’s already there.
StreamTooLong The file is bigger than your limit (or a line is bigger than your buffer).

writeFile and readFileAlloc are great for small files. When you want to write in many small pieces, or read a big file a bit at a time, open the file yourself and use a writer or reader with a buffer, exactly like stdout in Zig Output:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const cwd = std.Io.Dir.cwd();
const file = try cwd.createFile(io, "squares.txt", .{});
defer file.close(io);
var buffer: [1024]u8 = undefined;
var file_writer = file.writer(io, &buffer);
const w = &file_writer.interface;
for (1..6) |n| {
try w.print("{d} squared is {d}\n", .{ n, n * n });
}
try w.flush();
const size = (try cwd.statFile(io, "squares.txt", .{})).size;
std.debug.print("wrote {d} bytes\n", .{size});
try cwd.deleteFile(io, "squares.txt");
}

Output:

wrote 77 bytes
  • createFile creates the file (or empties an existing one) and opens it for writing. Use openFile instead to open a file that must already exist; it opens for reading unless you pass .{ .mode = .write_only } or .read_write.
  • An open file is a resource the operating system lends you, so give it back: defer file.close(io) on the very next line, every time.
  • file.writer(io, &buffer) and .interface give you the same *std.Io.Writer with print and writeAll you used for stdout.
  • flush before the file closes, or the last bytes stay in the buffer and never reach the disk. The file would be there, just shorter than you expected.
  • statFile returns information about a file without opening it: .size in bytes, .kind (.file, .directory, …) and modification time.

createFile and writeFile start from an empty file each time. To add to the end of a log instead, keep the old contents with .truncate = false and move the writer to the end before writing:

const std = @import("std");
fn appendLine(io: std.Io, path: []const u8, line: []const u8) !void {
const file = try std.Io.Dir.cwd().createFile(io, path, .{ .truncate = false });
defer file.close(io);
var buffer: [256]u8 = undefined;
var file_writer = file.writer(io, &buffer);
try file_writer.seekTo(try file.length(io)); // jump to the end
try file_writer.interface.print("{s}\n", .{line});
try file_writer.interface.flush();
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
const cwd = std.Io.Dir.cwd();
try appendLine(io, "log.txt", "started");
try appendLine(io, "log.txt", "did some work");
try appendLine(io, "log.txt", "finished");
const text = try cwd.readFileAlloc(io, "log.txt", init.gpa, .limited(4096));
defer init.gpa.free(text);
std.debug.print("{s}", .{text});
try cwd.deleteFile(io, "log.txt");
}

Output:

started
did some work
finished

createFile with .truncate = false creates the file the first time and keeps what’s there after that. file.length(io) is the current size, and seekTo moves the writer there, so new text lands after the old. Leave out the seekTo and the writer starts at the beginning and overwrites the first bytes instead. Notice that appendLine takes io as a parameter: functions that touch files need it passed in, just like the allocator.

For a big file, or one you process line by line anyway, read it with a buffered reader. It’s the same takeDelimiter loop you used for stdin in Zig Reading Input:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const cwd = std.Io.Dir.cwd();
try cwd.writeFile(io, .{
.sub_path = "scores.csv",
.data = "ada,92\nbob,78\n\ncy,85\n",
});
defer cwd.deleteFile(io, "scores.csv") catch {};
const file = try cwd.openFile(io, "scores.csv", .{});
defer file.close(io);
var buffer: [4096]u8 = undefined;
var file_reader = file.reader(io, &buffer);
const r = &file_reader.interface;
var total: u32 = 0;
var people: u32 = 0;
while (try r.takeDelimiter('\n')) |line| {
if (line.len == 0) continue;
const name, const score_text = std.mem.cutScalar(u8, line, ',') orelse continue;
const score = try std.fmt.parseInt(u32, score_text, 10);
std.debug.print("{s}: {d}\n", .{ name, score });
total += score;
people += 1;
}
std.debug.print("average: {d}\n", .{total / people});
}

Output:

ada: 92
bob: 78
cy: 85
average: 85

The program writes a small CSV file first so it has something to read. Then:

  • openFile(io, path, .{}) opens it for reading, and file.reader(io, &buffer) wraps it in a buffered reader. Only 4 KB of the file is in memory at a time, however big the file is.
  • takeDelimiter('\n') returns one line at a time and null at the end. Like with stdin, the line points into the reader’s buffer, so copy it if you need it after the next read.
  • std.mem.cutScalar(u8, line, ',') splits the line at the first comma into two slices, or returns null if there’s no comma (that line is skipped).
  • The two defers run in reverse order: the file is closed first, then deleted.

Folders work through the same Dir type. This program builds a small project folder, lists what’s inside it, and removes it again:

const std = @import("std");
fn lessThan(_: void, a: []const u8, b: []const u8) bool {
return std.mem.order(u8, a, b) == .lt;
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
const arena = init.arena.allocator();
const cwd = std.Io.Dir.cwd();
// Make some folders and files to look at.
try cwd.createDir(io, "project", .default_dir);
try cwd.createDirPath(io, "project/src/utils");
try cwd.writeFile(io, .{ .sub_path = "project/README.md", .data = "# hi\n" });
try cwd.writeFile(io, .{ .sub_path = "project/build.zig", .data = "" });
// List what's directly inside "project".
var dir = try cwd.openDir(io, "project", .{ .iterate = true });
defer dir.close(io);
var names: std.ArrayList([]const u8) = .empty;
var it = dir.iterate();
while (try it.next(io)) |entry| {
const label = try arena.print("{s} ({t})", .{ entry.name, entry.kind });
try names.append(arena, label);
}
std.mem.sort([]const u8, names.items, {}, lessThan);
for (names.items) |name| std.debug.print("{s}\n", .{name});
// Clean up.
try cwd.deleteTree(io, "project");
}

Output:

README.md (file)
build.zig (file)
src (directory)

Piece by piece:

  • createDir(io, "project", .default_dir) makes one folder. Its parent must exist. .default_dir is the usual permissions for a new folder.
  • createDirPath(io, "project/src/utils") makes every missing folder along the path, like mkdir -p, and it’s fine if they already exist.
  • To list a folder, open it with openDir and .iterate = true, then call iterate() and next(io) until it returns null. Each entry has a .name and a .kind. Close the folder when you’re done, like a file.
  • The operating system returns entries in no particular order, and it differs between machines. That’s why the program sorts the names before printing (Zig Sorting & Searching). Sort whenever the order matters to you.
  • entry.name points into the iterator’s own buffer, so the program copies each name (with arena.print) before keeping it.
  • deleteTree removes a folder and everything in it.

The gentler tools fail instead of guessing:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const cwd = std.Io.Dir.cwd();
try cwd.createDir(io, "box", .default_dir);
try cwd.writeFile(io, .{ .sub_path = "box/note.txt", .data = "hi" });
cwd.createDir(io, "box", .default_dir) catch |err| {
std.debug.print("createDir again: {t}\n", .{err});
};
cwd.deleteDir(io, "box") catch |err| {
std.debug.print("deleteDir: {t}\n", .{err});
};
try cwd.deleteFile(io, "box/note.txt");
try cwd.deleteDir(io, "box");
std.debug.print("box is gone\n", .{});
}

Output:

createDir again: PathAlreadyExists
deleteDir: DirNotEmpty
box is gone

createDir won’t make a folder that exists, and deleteDir only removes empty folders. Delete the files first, or use deleteTree when you really mean “all of it”.

iterate only looks one level deep. To visit everything below a folder, use walk, which goes into every subfolder for you:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const cwd = std.Io.Dir.cwd();
try cwd.createDirPath(io, "w/a/b");
try cwd.writeFile(io, .{ .sub_path = "w/a/b/x.txt", .data = "" });
defer cwd.deleteTree(io, "w") catch {};
var dir = try cwd.openDir(io, "w", .{ .iterate = true });
defer dir.close(io);
var walker = try dir.walk(init.gpa);
defer walker.deinit();
while (try walker.next(io)) |entry| {
std.debug.print("{s} ({t})\n", .{ entry.path, entry.kind });
}
}

Output:

a (directory)
a/b (directory)
a/b/x.txt (file)

entry.path is the path relative to the folder you started from. The walker needs an allocator to remember where it is, so it takes init.gpa and needs a deinit. As with iterate, the order isn’t guaranteed (this tree has only one entry per level, so it can’t vary), and each entry.path is only valid until the next next.

Write a program that writes a file poem.txt with three lines, then reads it back with a buffered reader and prints how many lines it has. Delete the file at the end.

Hint: writeFile for the setup, then openFile, file.reader(io, &buffer) and a takeDelimiter loop.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const cwd = std.Io.Dir.cwd();
try cwd.writeFile(io, .{ .sub_path = "poem.txt", .data = "roses\nviolets\nzig\n" });
defer cwd.deleteFile(io, "poem.txt") catch {};
const file = try cwd.openFile(io, "poem.txt", .{});
defer file.close(io);
var buffer: [1024]u8 = undefined;
var file_reader = file.reader(io, &buffer);
var lines: usize = 0;
while (try file_reader.interface.takeDelimiter('\n')) |_| lines += 1;
std.debug.print("poem.txt has {d} lines\n", .{lines});
}

Output:

poem.txt has 3 lines

|_| throws the line away, since only the count matters. The defers run newest first, so the file is closed before it’s deleted.

Write a program that keeps a number in count.txt. Each run reads the number (or starts from 0 if the file doesn’t exist), adds 1, writes it back and prints it. Make main call your function three times to see it count, then delete the file.

Hint: catch error.FileNotFound from readFileAlloc and use "0". std.mem.trim the text before parseInt, and write the new number with writeFile.

Show solution
const std = @import("std");
fn bump(io: std.Io, gpa: std.mem.Allocator) !u32 {
const cwd = std.Io.Dir.cwd();
const text = cwd.readFileAlloc(io, "count.txt", gpa, .limited(64)) catch |err| switch (err) {
error.FileNotFound => try gpa.dupe(u8, "0"),
else => return err,
};
defer gpa.free(text);
const count = try std.fmt.parseInt(u32, std.mem.trim(u8, text, " \r\n"), 10) + 1;
var buf: [16]u8 = undefined;
const new_text = try std.mem.print(&buf, "{d}\n", .{count});
try cwd.writeFile(io, .{ .sub_path = "count.txt", .data = new_text });
return count;
}
pub fn main(init: std.process.Init) !void {
defer std.Io.Dir.cwd().deleteFile(init.io, "count.txt") catch {};
for (0..3) |_| {
std.debug.print("visit number {d}\n", .{try bump(init.io, init.gpa)});
}
}

Output:

visit number 1
visit number 2
visit number 3

Using gpa.dupe for the default keeps one rule for text: it’s always allocated, so the single defer gpa.free(text) is always right. std.mem.print formats into a stack buffer, so writing the number needs no allocation.

  • File work starts from a folder: std.Io.Dir.cwd() is the folder you ran the program from, and every call takes io.
  • writeFile writes (and replaces) a whole file. readFileAlloc(io, path, gpa, .limited(n)) reads one; free the result, and keep the limit bigger than the file.
  • Handle error.FileNotFound with catch |err| switch (err) when a missing file is normal.
  • For bigger jobs, createFile/openFile, then defer file.close(io) and a buffered writer or reader. Flush before closing.
  • Append with .truncate = false plus seekTo(file.length(io)). Read big files line by line with takeDelimiter.
  • Folders: createDir/createDirPath, list with openDir(.{ .iterate = true }) (order isn’t guaranteed), remove with deleteFile/deleteDir, and deleteTree only when you mean it.

Next up: Zig JSON, turning file contents into structs and structs back into text with std.json.

Quick check

1. A program writes to a file through a buffered writer, closes it, and the file is shorter than expected. What's missing?
2. A file is exactly 100 bytes. What does readFileAlloc(io, path, gpa, .limited(100)) do?
3. You list a folder with iterate() twice on two computers and get the files in a different order. Why?
4. Which call removes a folder that still has files in it?