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
hello
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")});
}
hello
Advertisements
Everyday examples
Read the pickup code that the library saved for the next shift.
Startinput.txt
ResultB12
B12
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")});
}
B12
Read the room number that the teacher saved for the morning class.
Startinput.txt
ResultRoom 8
Room 8
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")});
}
Room 8
Show the next stop stored in the bus display file.
Startinput.txt
ResultOak Street
Oak Street
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")});
}
Oak Street