Create File in Zig if it Does Not Exist
In this blog post, we will break down a concise Zig program that demonstrates File I/O, error handling with catch and resource management using defer.
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const file_result = std.Io.Dir.cwd().createFile(
init.io,
"/tmp/empty.txt",
.{
.exclusive = true,
.truncate = false,
},
) catch |err| {
if (err == error.PathAlreadyExists) {
std.debug.print("File already exists.\n", .{});
return;
} else {
return err;
}
};
defer file_result.close(init.io);
std.debug.print("Created empty file.\n", .{});
}
The program begins by importing the standard library with const std = @import("std");, which provides essential tools for I/O operations, debugging, and process management. The main() function is declared as pub fn main(init: std.process.Init) !void, where the !void return type indicates it may produce an error and the init parameter supplies runtime I/O context.
Inside main(), the code attempts to create a new empty file at /tmp/empty.txt using std.Io.Dir.cwd().createFile(init.io, "/tmp/empty.txt", .{ .exclusive = true, .truncate = false }). The .exclusive = true option ensures the operation fails if the file already exists (returning error.PathAlreadyExists), while .truncate = false prevents clearing any existing content. This combination strictly enforces the creation of a brand-new file.
The entire createFile() call is wrapped in a catch |err| block that handles errors gracefully: if the specific error is PathAlreadyExists, it prints File already exists. and returns early; for any other error, it propagates the error by returning it directly. If creation succeeds, defer file_result.close(init.io); ensures the file handle is automatically closed when the function exits, preventing resource leaks regardless of how the scope ends. Finally, the program prints “Created empty file.” to confirm success.
Save the code as emptyIfNotExists.zig and execute it as follows:
$ zig run emptyIfNotExists.zig
Created empty file.
$ zig run emptyIfNotExists.zig
File already exists.
The first program execution created the file, hence the message of success, whereas the second program execute found that the file already exists, hence the relevant message.
Happy coding in Zig!