Skip to content
The Chat Archive
Claudeclaude-instant-1· Anthropic Arena Human Preference 55K

Show how to read a file line by line in Zig.

  1. User

    Show how to read a file line by line in Zig.

  2. Assistant

    Here is an example of how to read a file line by line in Zig:

    const std = @import("std");
    
    pub fn main() !void {
      var file = try std.fs.cwd().openFile("file.txt", .{});
    
      var buffer: [1024]u8 = undefined;
    
      while (try file.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
        std.debug.print("Line: {s}\n", .{line});
      }
    
      try file.close();
    }
    

    The key points:

    • Open the file for reading with std.fs.cwd().openFile()
    • Use file.readUntilDelimiterOrEof() to read each line into a buffer, delimited by newline
    • It returns an optional which is iterated over with the |line| syntax
    • Print out each line
    • Close the file after reading

    This allows iterating over the file line by line without having to manually handle buffering and newlines.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.