Skip to main content

File System API

The std.fs module provides file system operations for Zig. It includes functionality for working with files, directories, and paths across different operating systems.

Core Types

Dir

const Dir = @import("fs/Dir.zig");
Represents a directory handle for file system operations.
fd
posix.fd_t
The underlying file descriptor for the directory

File

const File = @import("fs/File.zig");
Represents an open file handle.

AtomicFile

const AtomicFile = @import("fs/AtomicFile.zig");
Provides atomic file operations to ensure data consistency.

Constants

max_path_bytes

pub const max_path_bytes: usize
The maximum length of a file path that the operating system will accept. The byte count includes room for a null sentinel byte.
max_path_bytes
usize
  • Windows: windows.PATH_MAX_WIDE * 3 + 1 (WTF-8 encoded)
  • POSIX: posix.PATH_MAX
  • Platform-specific maximum path length
Note: Paths may be longer than this length, but cannot be successfully passed to file system operations.

max_name_bytes

pub const max_name_bytes: usize
The maximum size of a file name component that the platform’s common file systems support.
max_name_bytes
usize
  • Linux/BSD: posix.NAME_MAX
  • Windows: windows.NAME_MAX * 3 (WTF-8 encoded)
  • Haiku: posix.NAME_MAX - 1

has_executable_bit

pub const has_executable_bit: bool
has_executable_bit
bool
true on POSIX systems, false on Windows and WASI

Directory Operations

cwd

pub fn cwd() Dir
Returns a handle to the current working directory.
return
Dir
Directory handle for the current working directory
Example:
const std = @import("std");
const current_dir = std.fs.cwd();
Note: Deprecated in favor of Io.Dir.cwd.

makeDirAbsolute

pub fn makeDirAbsolute(absolute_path: []const u8) !void
Creates a new directory based on an absolute path.
absolute_path
[]const u8
required
Absolute path where the directory should be created
  • Windows: WTF-8 encoded
  • WASI: Valid UTF-8
  • Other: Opaque byte sequence
Example:
try std.fs.makeDirAbsolute("/tmp/mydir");

openDirAbsolute

pub fn openDirAbsolute(absolute_path: []const u8, flags: Dir.OpenOptions) File.OpenError!Dir
Opens a directory at the given absolute path. The directory is a system resource that remains open until close is called.
absolute_path
[]const u8
required
Absolute path to the directory
flags
Dir.OpenOptions
required
Options for opening the directory
return
Dir
Opened directory handle
Example:
const dir = try std.fs.openDirAbsolute("/tmp", .{});
defer dir.close();

deleteDirAbsolute

pub fn deleteDirAbsolute(dir_path: []const u8) !void
Deletes a directory at the given absolute path.
dir_path
[]const u8
required
Absolute path to the directory to delete
Example:
try std.fs.deleteDirAbsolute("/tmp/mydir");

deleteTreeAbsolute

pub fn deleteTreeAbsolute(absolute_path: []const u8) !void
Removes a symlink, file, or directory recursively.
absolute_path
[]const u8
required
Absolute path to the file system entry to delete
Errors:
  • error.CannotDeleteRootDirectory - Attempt to remove the root file system path
Example:
try std.fs.deleteTreeAbsolute("/tmp/project");

File Operations

openFileAbsolute

pub fn openFileAbsolute(absolute_path: []const u8, flags: File.OpenFlags) File.OpenError!File
Opens a file for reading or writing without attempting to create a new file.
absolute_path
[]const u8
required
Absolute path to the file
flags
File.OpenFlags
required
Flags controlling how the file is opened
return
File
Opened file handle - call File.close() to release the resource
Example:
const file = try std.fs.openFileAbsolute("/tmp/data.txt", .{ .mode = .read_only });
defer file.close();

createFileAbsolute

pub fn createFileAbsolute(absolute_path: []const u8, flags: File.CreateFlags) File.OpenError!File
Creates, opens, or overwrites a file with write access.
absolute_path
[]const u8
required
Absolute path where the file should be created
flags
File.CreateFlags
required
Flags controlling file creation
return
File
Created file handle - call File.close() to release the resource
Example:
const file = try std.fs.createFileAbsolute("/tmp/output.txt", .{});
defer file.close();
try file.writeAll("Hello, World!");

deleteFileAbsolute

pub fn deleteFileAbsolute(absolute_path: []const u8) Dir.DeleteFileError!void
Deletes a file at the given absolute path.
absolute_path
[]const u8
required
Absolute path to the file to delete
Example:
try std.fs.deleteFileAbsolute("/tmp/tempfile.txt");

copyFileAbsolute

pub fn copyFileAbsolute(
    source_path: []const u8,
    dest_path: []const u8,
    args: Dir.CopyFileOptions,
) !void
Copies a file from source to destination.
source_path
[]const u8
required
Absolute path to the source file
dest_path
[]const u8
required
Absolute path to the destination
args
Dir.CopyFileOptions
required
Options for the copy operation
Example:
try std.fs.copyFileAbsolute("/tmp/source.txt", "/tmp/dest.txt", .{});

Path Operations

accessAbsolute

pub fn accessAbsolute(absolute_path: []const u8, flags: Io.Dir.AccessOptions) Dir.AccessError!void
Tests access to a path. Be careful of Time-Of-Check-Time-Of-Use race conditions.
absolute_path
[]const u8
required
Absolute path to test
flags
Io.Dir.AccessOptions
required
Access mode to test
Warning: Instead of testing if a file exists and then opening it, just open it and handle the error for file not found.

renameAbsolute

pub fn renameAbsolute(old_path: []const u8, new_path: []const u8) !void
Renames a file or directory.
old_path
[]const u8
required
Current absolute path
new_path
[]const u8
required
New absolute path
Example:
try std.fs.renameAbsolute("/tmp/old.txt", "/tmp/new.txt");

realpath

pub const realpath = posix.realpath;
pub const realpathZ = posix.realpathZ;
pub const realpathW = posix.realpathW;
Resolves a path to its canonical absolute form.

realpathAlloc

pub fn realpathAlloc(allocator: Allocator, pathname: []const u8) ![]u8
Resolves a path to its canonical form, allocating memory for the result.
allocator
Allocator
required
Allocator for the result
pathname
[]const u8
required
Path to resolve
return
[]u8
Caller owns the returned memory
  • Windows: WTF-8 encoded
  • Other: Opaque byte sequence
Example:
const allocator = std.heap.page_allocator;
const real = try std.fs.realpathAlloc(allocator, "../relative/path");
defer allocator.free(real);

symLinkAbsolute

pub fn symLinkAbsolute(
    target_path: []const u8,
    sym_link_path: []const u8,
    flags: Dir.SymLinkFlags,
) !void
Creates a symbolic link. A symbolic link may point to an existing file or to a nonexistent one (dangling link).
target_path
[]const u8
required
Absolute path that the symbolic link will point to
Absolute path where the symbolic link will be created
flags
Dir.SymLinkFlags
required
Flags for the symbolic link (e.g., is_directory on Windows)
Example:
try std.fs.symLinkAbsolute("/actual/file.txt", "/link/to/file.txt", .{});

readLinkAbsolute

pub fn readLinkAbsolute(pathname: []const u8, buffer: *[max_path_bytes]u8) ![]u8
Reads the target of a symbolic link.
pathname
[]const u8
required
Absolute path to the symbolic link
buffer
*[max_path_bytes]u8
required
Buffer to store the link target
return
[]u8
Slice of the buffer containing the link target
Example:
var buf: [std.fs.max_path_bytes]u8 = undefined;
const target = try std.fs.readLinkAbsolute("/tmp/link", &buf);

Executable Path

selfExePath

pub fn selfExePath(out_buffer: []u8) SelfExePathError![]u8
Gets the path to the current executable. Follows symlinks.
out_buffer
[]u8
required
Buffer to store the path
return
[]u8
Slice of the buffer containing the executable path
  • Windows: WTF-8 encoded
  • Other: Opaque byte sequence
Platform Notes:
  • Linux: Depends on procfs being mounted. If binary was deleted, path looks like /a/b/c/exe (deleted)
  • macOS: Uses _NSGetExecutablePath then realpath
Example:
var buf: [std.fs.max_path_bytes]u8 = undefined;
const exe_path = try std.fs.selfExePath(&buf);

selfExePathAlloc

pub fn selfExePathAlloc(allocator: Allocator) ![]u8
Like selfExePath but allocates the result on the heap.
return
[]u8
Caller owns returned memory

selfExeDirPath

pub fn selfExeDirPath(out_buffer: []u8) SelfExePathError![]const u8
Gets the directory path that contains the current executable. Example:
var buf: [std.fs.max_path_bytes]u8 = undefined;
const exe_dir = try std.fs.selfExeDirPath(&buf);

openSelfExe

pub fn openSelfExe(flags: File.OpenFlags) OpenSelfExeError!File
Opens the current executable for reading.
return
File
Open file handle to the current executable
Note: Deprecated in favor of Io.File.openSelfExe.

Application Data

getAppDataDir

pub const getAppDataDir = @import("fs/get_app_data_dir.zig").getAppDataDir;
Gets the platform-specific application data directory.

Base64 Encoding

base64_encoder

pub const base64_encoder: base64.Base64Encoder
Base64 encoder using -_ instead of +/ for filesystem-safe encoding.

base64_decoder

pub const base64_decoder: base64.Base64Decoder
Base64 decoder for filesystem-safe encoding. Example:
const encoded = try std.fs.base64_encoder.encode(allocator, "data");
const decoded = try std.fs.base64_decoder.decode(allocator, encoded);

Path Module

pub const path = @import("fs/path.zig");
Provides utilities for manipulating file paths:
  • path.isAbsolute() - Check if path is absolute
  • path.basename() - Get the last component of a path
  • path.dirname() - Get the directory part of a path
  • path.join() - Join path components
  • And more…

Error Sets

SelfExePathError

pub const SelfExePathError = error{
    FileNotFound,
    AccessDenied,
    NameTooLong,
    NotSupported,
    NotDir,
    SymLinkLoop,
    InputOutput,
    FileTooBig,
    IsDir,
    ProcessFdQuotaExceeded,
    SystemFdQuotaExceeded,
    NoDevice,
    SystemResources,
    NoSpaceLeft,
    FileSystem,
    BadPathName,
    DeviceBusy,
    SharingViolation,
    PipeBusy,
    NotLink,
    PathAlreadyExists,
    NetworkNotFound,
    ProcessNotFound,
    AntivirusInterference,
    UnrecognizedVolume,
    Canceled,
} || posix.SysCtlError;

Platform-Specific Notes

Windows

  • File paths are encoded as WTF-8
  • Antivirus software can cause AntivirusInterference errors
  • Maximum path length is PATH_MAX_WIDE * 3 + 1

WASI

  • File paths must be valid UTF-8
  • Default CWD is file descriptor 3

POSIX

  • File paths are opaque byte sequences
  • Maximum path length is PATH_MAX

Build docs developers (and LLMs) love