for Zig 0.15.2 Buy

CHAPTER 9

Files


We use the std library to work with the file system. You can read its documentation here:

https://ziglang.org/documentation/master/std/#std.fs


std.fs.


Creating files in an absolute path, handling errors

Many times, we’ll want to write files to an absolute path. Absolute paths specify the full path to a file. Relative paths assume we’re referring to a location inside the current working directory.

create_file.zig

const std = @import("std");

const print = std.debug.print;

pub fn main() !void {

    const s_dir = "/";

    const s_filename = "instructions.txt";

    const s_path = s_dir ++ s_filename;

    if (std.fs.createFileAbsolute(

        s_path,

        .{},

    )) |o_fx| {

        // we defer closing the file

        defer o_fx.close();

        print("File created\n", .{});

    } else |err_x| {

        // si hay un error lo imprimimos

        print(

            "Could not create file. Err: {s}.\n",

            .{@errorName(err_x)},

        );

    }

}

$ zig run create_file.zig

Could not create file. Err: AccessDenied.

The most common thing on a real machine is that we won't be allowed to create a file at the root of the file system for security reasons, unless we provide admin credentials. If that happens to you, try changing the write directory to /tmp/ and see what happens.

He pulled out his map. The beach stretched for kilometers in every direction. A true desert of sand, washed by the sea.

- It has to be around here -he thought. Everything pointed to the Temple of Orpheus, with its head on an altar, being nearby.

- Alright... This spot is as good as any to let you go -he said, opening the box he’d been carrying like a backpack for hours.

As he activated it - the bird took off, flapping its wings before its owner could even get a word out.

- We there yet? -squawked the corvoid, landing on his shoulder.

- We should be. Fly in a spiral. If you see anything that looks like an entrance or a door, let me know.

The bird took off ,as ordered. The inventor had barely sat down on the sand when the corvoid landed back on his shoulder, startling him.

- There's a door right in front of us, said the corvoid, with his pleasant baritone voice.

Writing files

We’re going to write a file to the /tmp/ directory, which is usually readable and writable by all users:

write_file.zig

const std = @import("std");

const print = std.debug.print;

pub fn main() !void {

    // create a file at an absolute path

    const o_file = try std.fs.createFileAbsolute(

        "/tmp/instructions.txt",

        .{},

    );

    defer o_file.close();

    const n_size = try o_file.write(

        \\ Hello,

        \\ These are the instructions

        \\ to duplicate a cube.

        \\ You’ll have to think in 3 dimensions.

        \\

        \\ Look at the formula for the volume of a cube: V = a³

        \\ The volume of the double cube is: V₂ = 2(a)³

        \\

        \\ To get the new side a₂

        \\ we know that a₂³ = 2(a³)

        \\ a₂ = ³√(2a³)

        \\ a₂ = a ³√2

        \\

        \\ This cube root of 2 is not a rational number,

        \\ it cannot be constructed with ruler and compass, with them

        \\ you can only construct lengths using addition, subtraction,

        \\ multiplication, division, and square roots.

        \\ But not cube roots.

        \\

        \\ Now, leave immediately through the entrance door.

        \\ It closes after 60 seconds.

        \\ If you exit through the other door,

        \\ you won’t remember any of this.

        \\ Thank the crow.

    );

    print("Wrote {} bytes\n", .{n_size});

}

$ zig run write_file.zig

Wrote … bytes

- Did you see that door that just disappeared behind you? - said the corvoid.

- No. - replied the inventor, confused, turning around as fast as he could. - But I see that door ahead, as you said.

- Well, whatever it is, I’ll say it again: something doesn’t add up, friend.

- I'm going in. Stay here.

- Don’t go in! That can’t be good! - shouted the crow, as his owner disappeared through the entrance once again.

- Look, turn around! Don’t you see the door disappearing? - shouted the crow again.

- No. -

- But…

- Yeah, yeah, but you see that door ahead and…

- I'm going to…

- …go in. - finished the crow.

- Hey, we finished the sentence at the same time. Stay here - smiled Archytas.

- No, I’m not planning to go in - replied the crow.

- Archy? Don’t you get a strange feeling - like you’ve lived this before? - asked the crow, seeing him come out for the umpteenth time from the door that vanished right after.

- No. Why?

- No, it’s nothing, friend. Go, run through the entrance door. I’ll stay here.

- Yeah, I was just about to say that - said the inventor.

- Hey, one more thing...

- Archytas, this has been fun and all, but we've been at it for hours.

- Yes, we've been walking for hours, but this is a unique chance to get answers. Answers Orpheus’s head knows, and we mere mortals do not.

- Archy, every time you go through that door, you show up a long while later through another one that disappears behind you. And you don’t remember what happened inside. You don’t even remember going in once, or this conversation.

Archytas fell silent for a moment, processing his friend’s words.

Reading files

If you wrote the file in the earlier example, you can now read it.

read_file.zig

const std = @import("std");

const print = std.debug.print;

pub fn main() !void {

    // open a file at an absolute path

    const o_file = try std.fs.openFileAbsolute(

        "/tmp/instructions.txt",

        .{},

    );

    defer o_file.close();

    // use an input buffer

    var a_buff: [4096]u8 = undefined;

    const n_size = try o_file.read(&a_buff);

    print("Read {} bytes.\n", .{n_size});

    print("{s}\n", .{a_buff[0..n_size]});

}

$ zig run read_file.zig

Read 731 bytes.

 Hello,

 These are the instructions

 to duplicate a cube...

As Archytas repeats this strange process, after watching him go in and come out once more, the crow sighed and said nothing as his friend entered the temple yet again. Even he, with his sarcastic personality, was starting to worry - before they got out of this loop, the plague-infected could find them.

But this time, in less than a minute, the inventor came back through the same entrance.

- Archy? You came back through the entrance.

- Yes. The Temple of Orpheus has an entrance that closes in one minute… and an exit. If you leave through the exit, you don’t remember anything. So no matter how many questions it answers, you never remember the answers.

- And how did you figure that out?

- I left myself a note, apparently. Orpheus is a kind of connected android head. Every time you enter, the system resets everything. I managed to bypass some security restrictions: during startup, you can’t use stdout, but you can write temporary files. I left one executable that writes to a temp file and another that reads it, with a note at startup.

- And what did the note say?

- We have to think differently in three dimensions. And something else...

The crow waited.

- Thank you.

- Then something’s off, Archy. You’d never say that - laughed the crow.

Chapter Summary
Directories
© 2025 - 2026 Zen of Zig