Skip to content

Instantly share code, notes, and snippets.

@hyrmn
Created January 27, 2020 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyrmn/457e57b45f46fd99a9b4c0fa01f79862 to your computer and use it in GitHub Desktop.
Save hyrmn/457e57b45f46fd99a9b4c0fa01f79862 to your computer and use it in GitHub Desktop.
Reading a file and counting carriage returns in Zig 0.5.x+master
const std = @import("std");
const os = std.os;
const fs = std.fs;
const File = std.fs.File;
pub fn main() !void {
const stdout = &std.io.getStdOut().outStream().stream;
//try stdout.print("Hello, {}!\n", .{"world"});
var file = try fs.openFileAbsolute("c:\\data\\bigsum.txt", File.OpenFlags{});
defer file.close();
var buffer: [128 * 1024]u8 = undefined;
var count: i32 = 0;
while (true) {
const read = try file.read(buffer[0..]);
if (read == 0) {
try stdout.print("{}\n", .{count});
break;
}
var i: usize = 0;
while (i < read) : (i += 1) {
if (buffer[i] == '\n') {
count += 1;
}
}
// for (buffer[0..read]) |byte| {
// if (byte == '\n') {
// count = count + 1;
// }
// }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment