Skip to content

Instantly share code, notes, and snippets.

@komuw
Last active February 11, 2024 01:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komuw/98111edb30262f0c34d93e3aa7f537ed to your computer and use it in GitHub Desktop.
Save komuw/98111edb30262f0c34d93e3aa7f537ed to your computer and use it in GitHub Desktop.
read a file in zig
const std = @import("std");
const os = std.os;
const warn = std.debug.warn;
pub fn main() !void {
var file = try os.File.openRead("/path/to/file.txt");
defer file.close();
const file_size = try file.getEndPos();
// why cant I use?
// var buffer: [file_size]u8 = undefined;
// ie, I only want to create a buffer that is same size as
// the file been read.
var buffer: [1024 * 4]u8 = undefined;
const bytes_read = try file.read(buffer[0..buffer.len]);
warn("{}", buffer[0..bytes_read]);
}
@komuw
Copy link
Author

komuw commented May 13, 2019

why cant I use?

var buffer: [file_size]u8 = undefined;

ie, I only want to create a buffer that is same size as the file been read.

@komuw
Copy link
Author

komuw commented May 13, 2019

answer on IRC: file_size is a runtime value, array lengths are by definition comptime known

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment