Library reference

Read a text file

Save the sample file beside the program. Read the whole file and print the line it contains.

Dir.readFileAlloc

Simple example

Read the word saved in the file.

Startinput.txt
Resulthello
input.txt
hello
lesson.zig
const std = @import("std");

pub fn main() !void {
    const text = try std.fs.cwd().readFileAlloc(std.heap.page_allocator, "input.txt", 1024);
    defer std.heap.page_allocator.free(text);
    std.debug.print("{s}\n", .{std.mem.trimEnd(u8, text, "\r\n")});
}
Output
hello
Advertisements

Everyday examples

Read the pickup code that the library saved for the next shift.

Startinput.txt
ResultB12
input.txt
B12
lesson.zig
const std = @import("std");

pub fn main() !void {
    const text = try std.fs.cwd().readFileAlloc(std.heap.page_allocator, "input.txt", 1024);
    defer std.heap.page_allocator.free(text);
    std.debug.print("{s}\n", .{std.mem.trimEnd(u8, text, "\r\n")});
}
Output
B12

Read the room number that the teacher saved for the morning class.

Startinput.txt
ResultRoom 8
input.txt
Room 8
lesson.zig
const std = @import("std");

pub fn main() !void {
    const text = try std.fs.cwd().readFileAlloc(std.heap.page_allocator, "input.txt", 1024);
    defer std.heap.page_allocator.free(text);
    std.debug.print("{s}\n", .{std.mem.trimEnd(u8, text, "\r\n")});
}
Output
Room 8

Show the next stop stored in the bus display file.

Startinput.txt
ResultOak Street
input.txt
Oak Street
lesson.zig
const std = @import("std");

pub fn main() !void {
    const text = try std.fs.cwd().readFileAlloc(std.heap.page_allocator, "input.txt", 1024);
    defer std.heap.page_allocator.free(text);
    std.debug.print("{s}\n", .{std.mem.trimEnd(u8, text, "\r\n")});
}
Output
Oak Street
Run the example
Terminal
zig run lesson.zig
Official documentation