Skip to content

Instantly share code, notes, and snippets.

@matu3ba
Created April 27, 2023 20:07
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 matu3ba/9a046d85f9e5307110db99ef1ebacb72 to your computer and use it in GitHub Desktop.
Save matu3ba/9a046d85f9e5307110db99ef1ebacb72 to your computer and use it in GitHub Desktop.
read file
fn openAndRead(alloc: std.mem.Allocator, in_file: []const u8) !void {
var f = std.fs.cwd().openFile(in_file, .{}) catch |err| {
fatal("unable to open file '{s}': {s}\n", .{ in_file, @errorName(err) });
};
defer f.close();
const stat = try f.stat();
if (stat.size > std.math.maxInt(u32))
return error.FileTooBig;
const source = try alloc.allocSentinel(u8, @intCast(usize, stat.size), 0);
errdefer alloc.free(source);
const amt = try f.readAll(source);
if (amt <= 1)
return error.EmptyFile;
if (amt != stat.size)
return error.UnexpectedEndOfFile;
_ = amt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment