From a8ee9f637eabc663839ac583c227b30fedecc9c9 Mon Sep 17 00:00:00 2001 From: Araozu Date: Mon, 13 May 2024 11:37:25 -0500 Subject: [PATCH] Read file --- .gitignore | 4 ++++ inputs_test/01 | 5 +++++ src/main.zig | 41 +++++++++++++++++++++++++++++++++-------- 3 files changed, 42 insertions(+), 8 deletions(-) create mode 100644 .gitignore create mode 100644 inputs_test/01 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a553fc9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +inputs +zig-out +zig-cache + diff --git a/inputs_test/01 b/inputs_test/01 new file mode 100644 index 0000000..4cba7d0 --- /dev/null +++ b/inputs_test/01 @@ -0,0 +1,5 @@ +1abc2 +pqr3stu8vwx +a1b2c3d4e5f +treb7uchet + diff --git a/src/main.zig b/src/main.zig index c8a3f67..e18b136 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,19 +1,44 @@ const std = @import("std"); +const print = std.debug.print; + pub fn main() !void { // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`) std.debug.print("All your {s} are belong to us.\n", .{"codebase"}); - // stdout is for the actual output of your application, for example if you - // are implementing gzip, then only the compressed bytes should be sent to - // stdout, not any debugging messages. - const stdout_file = std.io.getStdOut().writer(); - var bw = std.io.bufferedWriter(stdout_file); - const stdout = bw.writer(); + try day01part1(file_name(false, "01")); + try day01part1(file_name(true, "01")); +} - try stdout.print("Run `zig build test` to run the tests.\n", .{}); +fn day01part1(filename: []const u8) !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); - try bw.flush(); // don't forget to flush! + const file = try std.fs.cwd().openFile(filename, .{}); + defer file.close(); + + var buf_reader = std.io.bufferedReader(file.reader()); + const reader = buf_reader.reader(); + + var line = std.ArrayList(u8).init(allocator); + defer line.deinit(); + + const writer = line.writer(); + while (reader.streamUntilDelimiter(writer, '\n', null)) { + defer line.clearRetainingCapacity(); + + print(":D {s}\n", .{line.items}); + } else |err| switch (err) { + error.EndOfStream => {}, + else => return err, + } +} + +/// Creates an input file name at comptime +fn file_name(comptime is_test: bool, comptime day: []const u8) []const u8 { + const input_suffix = if (is_test) "_test/" else "/"; + return "inputs" ++ input_suffix ++ day; } test "simple test" {